Question
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.
Example
Given s = “Hello World”,
return 5.
Java Code
public static int lengthOfLastWord(String s) {
int r, l;
//忽略字符串s尾部的若干空格,遇到非空格字符或者到达字符串头则结束
for(r = s.length() - 1; r >= 0 && s.charAt(r) == ' '; --r);
//如果字符串s是个空串或只包含若干空格符,则不包含任何单词
if(r == -1) return 0;
//统计最后一个单词的长度,遇到空格或者到达字符串头则结束
for(l = r - 1; l >= 0 && s.charAt(l) != ' '; --l);
//r和l分别指向最后一个单词的尾和头(或头的前一位)
return (r - l);
}