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 = “Hello World”,
return 5.
思路:从字符串末尾向前遍历,直到遇见第一个不为空的字符,然后开始统计单词长度,知道遇到下一个空字符为止或是遍历到字符串开头。
C++实现:
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.size() - 1;
int sum = 0;
while(len > 0 && s[len] == ' '){
len--;
}
for(int i = len;i >= 0;--i){
if(s[i] != ' ')
sum++;
else
break;
}
return sum;
}
};