leetcode58——Length of Last Word

题目大意:输出所给字符串中最后一个单词的长度,如果没有单词输出0,注意字符串可能只由空格组成,或者最后一个单词后还有空格。

分析:字符串。简单,需要注意细节。

代码:

class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0;
int i = s.size() - 1;
while (i >= 0 && s[i] == ' ') //过滤掉字符串结尾的空格
i--;
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};

猜你喜欢

转载自blog.csdn.net/tzyshiwolaogongya/article/details/80149342