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
.
Seen this question in a real interview before?
Yes
最后一句话的长度
分析:
给定一个字符串s由大小写字母和空白符组成,返回最后一个单词的长度(如果最后一个词不存在,则返回0)
提示:一个单词背定义为仅有非空个字符组成的字符序列
这道题其实不难,唯一的小陷阱就是最后括号里面的提示,表明可能又很多的空格结尾,这样的话,我们只能返回0,所以,我们可以换个思路,从字符串尾部开始,排除空格,然后再到空格结束,这样,可以找出最后一个单词的长度。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
int count = 0;
while(s[len-1]==' ')
len--;
for(int i=len-1;i>=0;i--)
{
if(s[i]==' ')
break;
count++;
}
return count;
}
};