给定一个仅包含大小写字母和空格 ’ ’ 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: “Hello World”
输出: 5
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.empty())
{
return 0;
}
else
{
int count=0;
for(int i=s.size()-1;i>-1;i--)
{
if(char(s[i])!='\40') ## 如果不是空格
{
count++;
}
if((count!=0)&&(char(s[i])=='\40'))
{
return count;
}
}
return count;
}
}
};