884. Uncommon Words from Two Sentences*
https://leetcode.com/problems/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:
0 <= A.length <= 200
0 <= B.length <= 200
-
A
andB
both contain only spaces and lowercase letters.
C++ 实现 1
使用哈希表存储 A
和 B
中每个 word 的个数, 取其中个数为 1 的 word. 注意:
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
unordered_map<string, int> record;
stringstream ss1(A), ss2(B);
string word;
while (ss1 >> word) record[word] ++;
while (ss2 >> word) record[word] ++;
vector<string> res;
for (auto &p : record)
if (p.second == 1)
res.push_back(p.first);
return res;
}
};
C++ 实现 2
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
unordered_set<string> setA, setA1, setB, setB1;
stringstream ss1(A), ss2(B);
string word;
while (ss1 >> word) {
if (!setA.count(word))
setA.insert(word);
else
setA1.insert(word);
}
while (ss2 >> word) {
if (!setB.count(word))
setB.insert(word);
else
setB1.insert(word);
}
vector<string> res;
for (auto &p : setA)
if (!setB.count(p) && !setA1.count(p))
res.push_back(p);
for (auto &p : setB)
if (!setA.count(p) && !setB1.count(p))
res.push_back(p);
return res;
}
};