简单题,求给出的字符串的最后一个单词的长度,要注意的是字符串的末尾可能是空格,要跳过空格。
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 ch
aracter sequence consists of non-space characters only.
Example:
Input: "Hello World" Output: 5
代码为:
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
int tail = s.size() - 1;
int i = tail;
while(i >= 0 && s[i] == ' ')
i--;
while(i >= 0 && s[i] != ' ')
{
i--;
count++;
}
return count;
}
};