题目没有什么技术难度,但是挖了个坑,这个坑在其他题目也难倒了不少英雄好汉。吃了亏,这次我就长记性了。关键点在于:1.如果开头就是空格,跳过本次循环;2.结尾是空格,则此时统计单词长度的countChr为零。
class Solution {
public:
int countSegments(string s) {
int countChr = 0; int countWord = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == ' '){
if(countChr){
countWord++;
countChr = 0;
}else{
continue;
}
}else{
countChr++;
}
}
return countChr == 0? countWord : countWord+1;
}
};