Description:
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
.
可以从后往前检测,当查到空格时,继续往前检测,遇到字符时开始计算长度,后续再遇到空格意味着词语结束,计数结束。
代码如下:
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while(tail>=0 && s[tail]==' ') tail--;
while(tail>=0 && s[tail]!= ' '){
len++;
tail--;
}
return len;
}
};