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.)

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.

Example 1:

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

Example 2:

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

Note:

  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 即可,参见代码如下:

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 同步地址:

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

参考资料:

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 题目讲解汇总(持续更新中…)


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,试运营期间前五十位可享受半价优惠~)

×

Help us with donation