难度:Easy
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
以空格分割,然后找出最后一个空格之后是否有单词即可。
class Solution {public:int countSegments(string s) {int res=0;bool ischar=false;if(s.empty()) return res;if(s.size()==1) return s[0]!=' ';for(int i=1;i<s.length();i++)if((s[i]==' ') && (s[i-1] !=' ')){res++;//cout<<" "<< i<< res<<" "<<s[i]<<" "<<s[i-1]<<endl;ischar=false;}else if(s[i]!=' ')ischar=true;return res+ischar;}};
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了90.29%的用户