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
Runtime: 4 ms, faster than 9.28% of C++ online submissions for Number of Segments in a String.
Memory Usage: 4.7 MB, less than 0.65% of C++ online submissions forNumber of Segments in a String.
class Solution {
public:
int countSegments(string s) {
int length = s.length();
int i = 0;
int result = 0;
while(i < length) {
if(!isspace(s[i++])) {
++result;
while(!isspace(s[i++])){
if (i == length) {
break;
}
};
}
}
return result;
}
};