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 =
return
Given s =
"Hello World",return
5.public class Solution {
public int lengthOfLastWord(String s) {
int len = s.length();
if(0 == len)
return 0;
int l = 0;
int r = 0;
int retl = l;
int retr = r;
for(int i = 0; i < len; ++i){
if(Character.isLetter(s.charAt(i))){
r++;
}else{
if(l != r){
retl = l;
retr = r;
}
r++;
l=r;
}
}
// Error: You have to judge for the last time, if the sentence is ending with a word.
if(l != r){
retl = l;
retr = r;
}
return retr-retl;
}
}
No comments:
Post a Comment