1.题目
2.题解
2.1java split()函数
2.2字符串遍历
给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:
一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串
示例:
输入: "Hello World" 输出: 5来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/length-of-last-word 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
使用split()函数按" "将字符串拆分后,直接返回最后一个字符串的长度。
public class Solution58 { public int lengthOfLastWord(String s) { String[] strs = s.split(" "); if (strs.length == 0) { return 0; } else { return strs[strs.length - 1].length(); } } }先从后过滤掉空格找到单词尾部,再从尾部向前遍历,直至单词头部,最后两者相减为单词的长度。
public class Solution58 { public int lengthOfLastWord(String s) { if (s.length() == 0) { return 0; } int count = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == ' ' && count != 0) { return count; } else if (s.charAt(i) == ' ') { count = 0; } else { count++; } } return count; } } 时间复杂度:空间复杂度: