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;
}
};