描述:
给定一个字符串, 包含大小写字母、空格' '
,请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0
。
样例:
给定 s = "Hello World"
,返回 5
。
代码:
class Solution {
public:
/**
* @param s A string
* @return the length of last word
*/
int lengthOfLastWord(string& s) {
// Write your code here
int n = s.length();
int len = 0;
if(n < 1) return 0;
int i = n - 1;
while(i >= 0)
{
if(s[i] == ' ')
i--;
else
break;
}
if(i >= 0)
{
while(s[i] != ' ' && i >= 0)
{
len++;
i--;
}
return len;
}
else
return len;
}
};