434. Number of Segments in a String
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
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。