描述
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
the string does not contain any non-printable characters.
您在真实的面试中是否遇到过这个题?
是
样例
Example:
Input: "Hello, my name is John"
Output: 5
这道题判断的方式是,如果第一个字母不为空格或者前一个是空格,自己不是空格。
class Solution {
public:
/**
* @param s: a string
* @return: the number of segments in a string
*/
int countSegments(string &s) {
// write yout code here
int count=0;
for(int i=0;i<s.length();i++){
if(s[i]!=' '&&(i==0||s[i-1]==' '))
count++;
}
return count;
}
};