[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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索