[LeetCode] Uncommon Words from Two Sentences

884. Uncommon Words from Two Sentences

A sentence is a string of single-space separated words where 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.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
unordered_map<string,int> helper(string& s) {
s.push_back(' ');
string now = "";
unordered_map<string,int> res;
for(auto& ch : s) {
if(ch == ' ') {
res[now]++;
now = "";
} else now.push_back(ch);
}
return res;
}
public:
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string,int> f1 = helper(s1), f2 = helper(s2);
vector<string> res;
for(auto& [k,v] : f1) if(v == 1 and f2.count(k) == 0) res.push_back(k);
for(auto& [k,v] : f2) if(v == 1 and f1.count(k) == 0) res.push_back(k);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/17/PS/LeetCode/uncommon-words-from-two-sentences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.