题目:434. 字符串中的单词数
题目描述:
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 “Hello,” 算作 1 个单词。
一、正常思路
count记录单词数量,为了防止有空字符串或者连续多个空格的情况,
加一个flag作为条件限定,由于正常情况n个空格对应n+1个单词,所以flag初值要设定为1
C++版本:
class Solution {
public:
int countSegments(string s) {
int count=0;
int flag=1;
for(int i=0;i<s.size();++i){
if(s[i]!=' '&&flag){
count++;
flag=0;
}
if(s[i]==' ') flag=1;
}
}
};
Python版本:
class Solution(object):
def countSegments(self, s):
flag=1
count=0
for i in range(len(s)):
if s[i]!=' 'and flag==1:
count=count+1
flag=0
if s[i]==' ':
flag=1
return count
二、不同语言的特殊方法
使用C++中标准IO库里的stringstream进行单词切分
C++版本:
class Solution {
public:
int countSegments(string s) {
int count=0;
string str;
stringstream ss;
ss<<s; //或者把两行并成一行 stringstream ss(s)
while(ss>>str){
count++;
}
return count;
}
};
Python_Oneline:使用Python内置split函数
class Solution(object):
def countSegments(self, s):
return len(split(s))
总结
C++ stringstream
作用:类型转换,词句转换
一. stringstream 一般可以用来实现安全的数据类型转换:
以int 类型为例
int 类型转string 类型
int a = 50;
string b;
stringstream ss;
ss << a;
ss >> b;// 转换后 b=“50”;
- string 类型转int int a ; string b = “100”; stringstream ss; ss << b; ss >> a;
// a= 100
二. 利用stringstream 实现句子与单个单词之间的转换;
句子 转为单个的词 string a =“how old are you , dear ?”; stringstream ss; ss << a; string b; while(ss >> b) {
cout <<b<<endl; }单个的词拼接为句子
stringstream ss;
ss << “how”<<" “<<“old”<<” “<<“are”<<” “<<“you”<<” “<<”,"<<“dear”<<" “<<”?";
string b;
b = ss.str();
cout<<b<<endl;