https://leetcode.com/problems/number-of-segments-in-a-string/
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John" Output: 5
代码:
class Solution {
public:
int countSegments(string s) {
s += ' ';
int len = s.length();
int ans = 0;
for(int i = 0; i < len; i ++) {
if(s[i] == ' ') continue;
ans ++;
while(i < len && s[i] != ' ') i ++;
}
return ans;
}
};
遍历字符串 判断空格之间夹的就是单词了 之前做过 HDU 的单词数 和这个差不多啦