[LeetCode] 884. Uncommon Words from Two Sentences 两个句子中不相同的单词



We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)html

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.git

Return a list of all uncommon words. github

You may return the list in any order.app

Example 1:函数

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]

Example 2:this

Input: A = "apple apple", B = "banana"
Output: ["banana"]

Note:spa

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A and B both contain only spaces and lowercase letters.



这道题给了咱们两个字符串,表示两个句子,每一个句子中都有若干个单词,用空格隔开,如今让咱们找出两个句子中惟一的单词。那么只要把每一个单词都提取出来,而后统计其在两个句子中出现的个数,若最终若某个单词的统计数为1,则其必定是符合题意的。因此咱们能够先将两个字符串拼接起来,中间用一个空格符隔开,这样提取单词就更方便一些。在 Java 中,能够使用 split() 函数来快速分隔单词,可是在 C++ 中就没这么好命,只能使用字符串流 istringstream,并用一个 while 循环来一个一个提取。当创建好了单词和其出现次数的映射以后,再遍历一遍 HashMap,将映射值为1的单词存入结果 res 便可,参见代码以下:code


class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        vector<string> res;
        unordered_map<string, int> wordCnt;
        istringstream iss(A + " " + B);
        while (iss >> A) ++wordCnt[A];
        for (auto a : wordCnt) {
            if (a.second == 1) res.push_back(a.first);
        }
        return res;
    }
};



Github 同步地址:htm

https://github.com/grandyang/leetcode/issues/884blog



参考资料:

https://leetcode.com/problems/uncommon-words-from-two-sentences/

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158967/C%2B%2BJavaPython-Easy-Solution-with-Explanation

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158981/Java-3-liner-and-5-liner-using-HashMap-and-HashSets-respectively.



LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索