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
.
遍历每个字符,每次保存刚刚遍历过的字的长度。注意字符串最后有空格和没空格两种情况结果储存在不同变量中。
public class Solution {
/**
* @param s A string
* @return the length of last word
*/
public int lengthOfLastWord(String s) {
int len = 0, prev = 0;
char[] str = s.toCharArray();
for(int i = 0; i < str.length; i++) {
if(str[i] != ' ') {
len ++;
}
if(str[i] == ' ') {
while(i + 1 < str.length && str[i + 1] == ' ') i++;
prev = len;
len = 0;
}
}
return len != 0 ? len : prev;
}
}