题目连接:Leetcode 058 Length of Last Word
解题思路:先将末尾的空白字符删除,然后逐一统计每个单词的长度,最后一个即为答案。
/*
* special case: "a "
*/
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size(), c = 0;
while (n && s[n-1] == ' ') n--;
for (int i = 0; i < n; i++) {
if (s[i] == ' ') c = 0;
else c++;
}
return c;
}
};