Powered By GitBook
434.Number of Segments in a String

434.Number of Segments in a String

难度: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.
1
Example:
2
3
Input: "Hello, my name is John"
4
Output: 5
Copied!
以空格分割,然后找出最后一个空格之后是否有单词即可。
1
class Solution {
2
public:
3
int countSegments(string s) {
4
int res=0;
5
bool ischar=false;
6
if(s.empty()) return res;
7
if(s.size()==1) return s[0]!=' ';
8
9
for(int i=1;i<s.length();i++)
10
if((s[i]==' ') && (s[i-1] !=' '))
11
{
12
res++;
13
//cout<<" "<< i<< res<<" "<<s[i]<<" "<<s[i-1]<<endl;
14
ischar=false;
15
}
16
else if(s[i]!=' ')
17
ischar=true;
18
19
return res+ischar;
20
}
21
};
Copied!
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了90.29%的用户
Last modified 2yr ago
Copy link