0%

number-of-segments-in-a-string

Number of Segments in a String – LeetCode 434

Problem

Description

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

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int countSegments(string s) {
int res = 0, n = s.size();
for (int i = 0; i < n; ++i) {
if (s[i] == ' ') continuea;
++res;
while (i < n && s[i] != ' ') ++i;
}
return res;
}
};

思路

只要检测空格就行了。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$2$ ms,排名$64.02\%$

Better

思路

还没看到更好的思路。