String里最后一个单词的长度
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
.
Given s = "Hello World"
, return 5
.
从末尾向前看
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int count = 0;
int i = s.length() - 1;
while(s.charAt(i) == ' ') {
--i;
}
while(s.charAt(i) != ' ') {
count++;
if(!(--i >= 0)) {
break;
}
}
return count;
}
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0) {
return 0;
}
String[] array = s.split(" ");
if(array.length == 0) {
return 0;
}
return array[array.length - 1].length();
}
思路:
从末尾向前看是,string末尾可能都是空格。