描述
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;
}
};