题目:
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
思路:
一道练手的题目。需要注意你的代码可以覆盖各种特殊情况(例如字符串中含有两个相邻的空格,以及字符串的开头和末尾有空格等等)。算法的时间复杂度是O(n),空间复杂度是O(1),其中n是字符串的长度。
代码:
class Solution {
public:
int countSegments(string s) {
int ret = 0;
bool start = false;
for (auto c : s) {
if (c == ' ') {
if (start) { // a segment ended
++ret, start = false;
}
}
else {
if (!start) { // a segment started
start = true;
}
}
}
if (start) { // a segment ended at the end
++ret;
}
return ret;
}
};