LeetCode-两句话中的不常见单词(stringstream的使用)

例题

句子是一串由空格分隔的单词。每个单词仅由小写字母组成,如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
给你两个句子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;

运行结果展示
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值