题目要求:
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
.
解答比较简单,唯一需要注意的是对在统计last word length前后,对空格的判断
代码如下:
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
if(len == 0)
return 0;
int k = 0;
int flag = 0;
for(int i = 0; i < len; i++)
{
if(s[len - i - 1] == ' ' && flag == 0)
continue;
else if(s[len - i - 1] == ' ' && flag == 1)
break;
else if(s[len - i - 1] != ' ')
{
k++;
flag = 1;
}
}
return k;
}
};