[LeetCode] Number of Segments in a String

434. Number of Segments in a String

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int countSegments(string s) {
int res = 0;
bool fl = 0;
s.push_back(' ');
for(auto& ch : s) {
if(ch == ' ') {
if(fl) res += 1;
fl = 0;
} else fl = 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/10/PS/LeetCode/number-of-segments-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.