题目
句子是一串由空格分隔的单词。每个单词仅由小写字母组成。
如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
给你两个 句子 s1 和 s2 ,返回所有不常用单词的列表。返回列表中单词可以按任意顺序组织。
来源:力扣(LeetCode)
解答
先将s1和s2两个句子,拆分成单词,并分别存入自己对应的哈希表中,哈希表key=单词,value=单词出现的次数。
然后分别遍历两个哈希表,遍历当前哈希表时,其出现次数为1且在另一个哈希表中没有出现,则将其添加到返回队列中。
代码如下:
class Solution {
public:
    vector<string> uncommonFromSentences(string s1, string s2) {
        unordered_map<string, int> mp1;
        unordered_map<string, int> mp2;
        stringstream ss1(s1);
        stringstream ss2(s2);
        string tmp;
        vector<string> ret;
        while (getline(ss1, tmp, ' ')) {
            mp1[tmp]++;
        }
        while (getline(ss2, tmp, ' ')) {
            mp2[tmp]++;
        }
        for (const auto &i: mp1) {
            if (i.second > 1) {
                continue;
            }
            auto it = mp2.find(i.first);
            if (it == mp2.end()) {
                ret.push_back(i.first);
            }
        }
        for (const auto &i: mp2) {
            if (i.second > 1) {
                continue;
            }
            auto it = mp1.find(i.first);
            if (it == mp1.end()) {
                ret.push_back(i.first);
            }
        }
        return ret;
    }
};

京公网安备 11010502036488号