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:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
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/
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)