题目描述:

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:

1
2
Input: "Hello, my name is John"
Output: 5

比较简单,注意处理连续的空格和结尾。还有有符号数与无符号数的隐式转换问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int countSegments(string s) {
int prevIndex = -1, ans = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] == ' '){
if(prevIndex != i - 1){
ans++;
}
prevIndex = i;
}
}
if(prevIndex < (int)s.length() - 1) ans++;
return ans;
}
};