public int lengthOfLastWord(String s) {
if (s== null || s.length()==0) return 0;
int end = s.length()-1;
while (end >=0 && s.charAt(end) == ' ') {
end--;
}
int start = end;
while (start >=0 && s.charAt(start) != ' ') {
start--;
}
return end-start;
}
public int lengthOfLastWord(String s) {
if (s==null ||s.length()==0) return 0;
int end = s.length()-1;
//Scan from the last character and skip all the whitespace
while (end>=0 && Character.isWhitespace(s.charAt(end))) {
end--;
}
//Already scan all the string return 0
int start = end;
while (start>=0 && !Character.isWhitespace(s.charAt(start))) {
start--;
}
return end - start;
}
No comments:
Post a Comment