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

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 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM