Problem:
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
思路:
Solution (C++):
int countSegments(string s) {
int res = 0;
s.push_back(' ');
for (int i = 1; i < s.length(); ++i) {
if (s[i] == ' ' && s[i-1] != ' ') ++res;
}
return res;
}
性能:
Runtime: 0 ms Memory Usage: 6.4 MB
思路:
Solution (C++):
int countSegments(string s) {
stringstream ss(s);
int res = 0;
while (ss >> s) ++res;
return res;
}
性能:
Runtime: 0 ms Memory Usage: 6.1 MB