Number of Segments in a String
Problem
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.
Constraints
0 <= s.length <= 300
s
consists of lowercase and uppercase English letters, digits, or one of the following characters"!@#$%^&*()_+-=',.:"
.- The only space character in
s
is' '
.
Solution
The problem Number of Segments in a String
can be solved by counting the number of non-space character that appears right after a space character.
Implementation
class Solution
{
public:
int countSegments(string s)
{
int ret = 0;
s = ' ' + s;
for (int i = 0; i < s.length() - 1; i++)
if (s[i + 1] != ' ' && s[i] == ' ')
ret += 1;
return ret;
}
};