884. Uncommon Words from Two Sentences

梦想的初衷 提交于 2020-01-28 08:08:16

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

给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的

返回所有不常用单词的列表。

您可以按任何顺序返回列表。

 

    示例 1:

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

    示例 2:

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

     

    提示:

    1. 0 <= A.length <= 200
    2. 0 <= B.length <= 200
    3. A 和 B 都只包含空格和小写字母。

    解法一

    //时间复杂度O(n), 空间复杂度O(n)
    class Solution {
    public:
        vector<string> uncommonFromSentences(string A, string B) {
            unordered_map<string, int> um;
            istringstream iss(A + ' ' + B);
            while(!iss.eof()) {
                string str;
                iss >> str;
                um[str]++;
            }
            vector<string> res;
            for(auto p : um) {
                if(p.second == 1 && !p.first.empty()) res.push_back(p.first);
            }
            return res;
        }
    };

    解法二

    class Solution {
    public:
        void countStr(unordered_map<string, int>& um, string& str) {
            string s = "";
            for(char c : str) {
                if(c != ' ') s += c;
                else {
                    if(s != "") um[s]++;
                    s = "";
                }
            }
            if(s != "") um[s]++;
        }
        vector<string> uncommonFromSentences(string A, string B) {
            int n1 = A.size(), n2 = B.size();
            unordered_map<string, int> um;
            countStr(um, A);
            countStr(um, B);
            vector<string> res;
            for(auto p : um) {
                if(p.second == 1) res.push_back(p.first);
            }
            return res;
        }
    };

    使用哈希表对两个句子中的单词计数,然后遍历哈希表,找出出现次数为1的单词,返回。

    解法一使用了istringstream(16ms,可能是因为A + ' ' + B这一步,字符串拼接比较耗时);

    解法二直接遍历字符(8ms)。

    2019/07/25 17:15
    标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!