[LeetCode]58. Length of Last Word
题目描述
思路
遇到空格,将计数器置为0
考虑字符串后多个空格的情况,加一个pre值,将count置0之前,检查count不为0,则将count赋给pre
最后返回,若count为0则返回pre,否则返回count
代码
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0, pre;
for(char &p : s) {
if(p == ' ') {
if(count)
pre = count;
count = 0;
}
else
++count;
}
return count ? count : pre;
}
};