The idea is to loop from the end of the String, and count char sequence before first space. Anyway, a flag or String,trim() is used to avoid spaces before the last word.
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null){
return 0;
}
int i = s.length() - 1;
int count = 0;
boolean isLastWord = false;
while(i >= 0){
if(s.charAt(i)!=' '){
isLastWord = true;
count++;
}else{
if(isLastWord){
break;
}
}
i--;
}
return count;
}
}
没有评论:
发表评论