原题链接
解析:
方法一:
使用python直接进行分割,之后返回分割后的数量即可,时间16ms:
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
方法二:
使用c++的字符串进行操作,判断当前不是空格但下一个位置是空格,时间0ms:
class Solution {
public:
int countSegments(string s) {
s += ' ';
int len = s.length();
int cnt = 0;
for(int i=0; i<len-1; i++)
{
if(s[i] != ' ' && s[i+1] == ' ')
cnt++;
}
return cnt;
}
};