题目:
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
解释:
直接按照空格分割就好,都不需要替换逗号之类的。
python代码:
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
c++代码:
#include <iostream>
using namespace std;
class Solution {
public:
int countSegments(string s) {
istringstream ss(s);
int count=0;
string word="";
while(getline(ss,word,' '))
{
if(word!="")
count+=1;
}
return count;
}
};
总结:
注意c++代码的时候需要判断一下word
是不是""
,因为python是可以用多个空格分割的但是c++只能用一个' '
分割。