length of last word


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.

For example,
Given s = "Hello World",
return 5.


我的解法:

1
2
3
4
5
6
7
8
9
public class {
public int lengthOfLastWord(String s) {
if (s.trim().length() == 0) {
return 0;
}
String[] strs = s.split(" ");
return strs[strs.length-1].length();
}
}

思想:为0的case判断,不为0则split开后取最后一个元素拿长度即可,题目简单,主要是0的判断。


一行解法:

1
2
3
4
5
public class {
public int lengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
}

思想:字符串长度减去最后一个空格的位置再减1。