题目描述:
给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。
您可以按任何顺序返回列表。
示例 1:
输入:A = “this apple is sweet”, B = “this apple is sour”
输出:[“sweet”,“sour”]
示例 2:
输入:A = “apple apple”, B = “banana”
输出:[“banana”]
提示:
0 <= A.length <= 200
0 <= B.length <= 200
A 和 B 都只包含空格和小写字母。
方法1:
主要思路:
(1)将两个字符串合并(注意中间加空格),对合并后的字符串进行分割统计,找出各个单词,使用unordered_map进行统计,最后找出统计中只出现一次的单词,即为不常见的单词;
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
int cur_pos=0;
unordered_map<string,int> mp;
A+=" "+B;//合并两个字符串,注意空格
//统计各个单词出现的频率
for(int i=0;i<A.size();++i){
while(i<A.size()&&A[i]!=' '){
++i;
}
++mp[A.substr(cur_pos,i-cur_pos)];
cur_pos=i+1;
}
//将只出现一次的单词统计出来
vector<string> res;
for(auto it=mp.begin();it!=mp.end();++it){
if(it->second==1){
res.push_back(it->first);
}
}
return res;
}
};