(2022.01.30)每日一题 两句话中不常见的单词
快过年了,自己想偷个懒做个leetcode,没想到leetcode也给我们放假,上来就是一道简单题。啪一下,哈希表,存储遍历。秒杀,思路和官方题解一致,但是代码写的比官方题解垃圾多了。
直接上代码了
//mine
class Solution {
public:
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string ,int> wordCount;
string temp;
vector<string> res;
//first
for(istringstream iss(s1); iss>>temp;){
wordCount[temp] += 1;
}
for(istringstream iss(s2); iss>>temp;){
wordCount[temp] += 1;
}
for(auto& word : wordCount){
if(word.second == 1){
res.push_back(word.first);
}
}
return res;
}
};
//official
class Solution {
public:
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string, int> freq;
auto insert = [&](const string& s) {
stringstream ss(s);
string word;
while (ss >> word) {
++freq[move(word)];
}
};
insert(s1);
insert(s2);
vector<string> ans;
for (const auto& [word, occ]: freq) {
if (occ == 1) {
ans.push_back(word);
}
}
return ans;
}
}