884. 两句话中的不常见单词

题目:给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。返回所有不常用单词的列表。

示例 1:

输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]
示例 2:

输入:A = "apple apple", B = "banana"
输出:["banana"]

题解:

 

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        unordered_map<string, int> mymap;
        A = A + " " + B;
        //istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。
        istringstream words(A);
        string w;
        vector<string> ans;
        while (words >> w) ++mymap[w];
        for (auto m : mymap) 
            if (m.second == 1) ans.push_back(m.first);
        return ans;
    }
};

作者:heygary
链接:https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/solution/c-zhong-gui-zhong-ju-de-0msjie-fa-bao-li-by-gary-6/

 

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        unordered_map<string,int> hash;
        stringstream ssA(A);
        stringstream ssB(B);
        string word;
        while(ssA >> word)
            hash[word]++;
        while(ssB >> word)
            hash[word]++;
        vector<string> res;
        for(auto iter: hash)
            if(iter.second == 1)
                res.emplace_back(iter.first);
        return res;
    }
};

作者:xing-chen-da-hai-36
链接:https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/solution/c-zi-fu-liu-ha-xi-biao-by-xing-chen-da-hai-36/
posted @ 2021-03-22 12:55  USTC丶ZCC  阅读(51)  评论(0)    收藏  举报