题目描述
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 res=0, i=0,last=0;
while(i<s.size()) {
if(s[i]==' ') {
last=res==0?last:res;
res=0;
}
else res++;
i++;
}
if(res==0 && last>0) return last;
return res;
}
};