原题:
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
其实就是数空格,但是我怕他例子里有连续空格这种,设置了一个ready标志,遇到非空格的ready设为有效,这时如果碰到空格则+1并重置ready为无效,最后输出前检查一次ready,无效说明末尾有空格应该-1,这样也能防止空串输出1,结果:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number of Segments in a String.
Memory Usage: 8.2 MB, less than 86.21% of C++ online submissions for Number of Segments in a String.
代码:
class Solution {
public:
int countSegments(string s) {
bool ready=0;
int cnt=1;
for(int i=0;i<s.size();i++){
if(s[i]!=' '){ready=1;}
else if(ready&&s[i]==' '){cnt++;ready=0;}
}
if(!ready){cnt--;}
return cnt;
}
};