434. Number of Segments in a String*
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
434. Number of Segments in a String*
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
C++ 实现 1
使用 stringstream 最简单.
class Solution {
public:
int countSegments(string s) {
stringstream ss(s);
string word;
int count = 0;
while (ss >> word) count ++;
return count;
}
};
C++ 实现 2
双指针.
class Solution {
public:
int countSegments(string s) {
int count = 0;
for (int i = 0; i < s.size(); ++ i) {
if (s[i] != ' ') {
int j = i;
while (j + 1 < s.size() && s[j + 1] != ' ') ++ j;
count ++;
i = j;
}
}
return count;
}
};