一开始以为如果最后一个字符是space就不存在最后一个单词,WA了一次。
遍历该string,cnt记录当前单词的长度,如果遇到space,还要判断它的下一个字符是不是space,是的话就重置cnt为0,否则不变。
class Solution {
public:
int lengthOfLastWord(const char *s) {
int len = strlen(s);
int cnt = 0;
for(int i = 0; i < len; i++){
if(s[i] == ' ' && i != len-1 && s[i+1] != ' '){
cnt = 0;
}
else if(s[i] != ' '){
cnt++;
}
}
return cnt;
}
};