https://oj.leetcode.com/problems/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.
public int lengthOfLastWord(String s)
分析,这题实在是太简单了,简单到我觉得用split甚至是trim都是犯规的。。从尾到头扫,用一个Boolean作为flag来判断是否进入最后一个单词的势力范围,然后开始计数,然后返回答案.....
public int lengthOfLastWord(String s) {
int counter = 0;
boolean firstPass = false;
for(int i = s.length() - 1; i >= 0; i--){
if(s.charAt(i) == ' '){
if(firstPass)
break;
}else{
firstPass = true;
counter++;
}
}
return counter;
}