1,题目要求
We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.
分别找出和两个字符串中各在一个中出现一次而在另一个没有出现的单词。
2,题目思路
对于这道题,目的是找到在一个字符串中仅仅出现一次,而在另一个字符串中没有出现的单词。因此,这里涉及到了不同单词的数量统计问题。而对于这样的问题,一般都会使用一个hashMap来进行实现。也就是unordered_map来辅助实现。
在一个字符串出现一次,在另一个没出现,其实就是说,对于两个字符串所组成的整个字符串而言,只要出现了一次的单词,就一定是满足条件的单词了。
于是,我们就可以对这个长字符串进行遍历,然后找到其中仅仅出现一次的单词,最后返回即可。
3,程序源码
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
unordered_map<string, int> cnt;
vector<string> res;
string total = A + " " + B, tmp = "";
istringstream in(total);
while(in>>tmp)
cnt[tmp]++;
for(auto c : cnt)
{
if(c.second == 1) res.push_back(c.first);
}
return res;
}
};