例题
句子是一串由空格分隔的单词。每个单词仅由小写字母组成,如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
给你两个句子S1和S2,返回所有不常用单词的列表。返回单词例表按图字典序排琼。
示例1: 输入:{“s1”:“this apple is sweet’”,“s2”:“this apple is sour”}
输出:[“sour”,"sweet’]
示例2:输入:{“s1”:“apple apple’”,“s2”:“banana”} 输出:[“banana”]
提示
1 <=s1.length,s2.length <=200
s1和s2由小写英文字母和空格组成
s1和s2都不含前导或尾随空格
s1和s2中的所有单词间均由单个空格分隔
#include <vector>
#include <map>
#include <sstream>
using namespace std;
class Solution{
public:
vector<string>uncommonFromSentence (string s1,string s2){
map<string,int>mp;
stringstream ss1(s1);
stringstream ss2(s2);
string str;
while(ss1 >> str){
mp[str]++;
}
while(ss2 >> str){
mp[str]++;
}
vector<string> result;
for(auto i = mp.begin();i != mp.end(); i++){
if(i->second == 1)
result.push_back(i->first);
}
sort (result.begin(),result.end());
return result;
}
};
stringstream的用法
1.可用于string与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
2.可用于句子与单个单词间的转换
句子转换成单词
string a ="how are you , madam ?";
stringstream ss;
ss << a;
string b;
while(ss >> b){
cout <<b<<endl;
}
运行结果展示
单词转换成句子
stringstream ss;
ss << "how"<<" "<<"are"<<" "<<"you"<<" "<<","<<"madam"<<" "<<"?";
string b;
b = ss.str();
cout<<b<<endl;
运行结果展示