Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: “Hello World”
Output: 5
给出一个string,要求return最后一个单词的长度,分隔符是space,如果没有最后一个单词,就返回0
乍一看很简单,不就是split
string[] result = s.split(" ");
return result[result.length - 1].length();
但是s=space时,result.length就会=0,然后就会ArrayIndexOutOfBounds
再者这种方法time上只超过60%
然后参照别人的一种方法,就是利用lastIndexOf(’ ')
并利用s.trim(),
但是注意s.trim()一定要保存到s,否则s是不变的
还有要注意是 s.length() -1 - index 而不是 s.length() - index,因为不包括‘ ’本身
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
s = s.trim();
int index = s.lastIndexOf(' ');
return index == -1 ? s.length() : s.length() -1 - index;
}