题目
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
思考
通过空格来判断字符串分多少部分,主要是考虑多种特殊情况(比如全空格等)。
答案
c++
class Solution {
public:
int countSegments(string s) {
if (s.length() == 0) return 0;
int result = 0;
for (int i = 1; i < s.length(); i++) {
if (s[i] == ' ' && s[i-1] != ' ') {
result++;
}
}
if (s[s.length()-1] != ' ') {
result++;
}
return result;
}
};