从Leetcode每日一题练习 ------ 539. 最小时间差继续讨论:
884. 两句话中的不常见单词
884. Uncommon Words from Two Sentences
题解
本题读懂题目可以发现, 实际上只是要求记下所有在所有字符串中均只出现了一次的单词, 最终返回这些单词. 则先将字符串按空格分割, 再使用map记录所有单词出现的次数, 将单词作为key, 出现次数作为value. 最终遍历map并将只出现一次的单词放入数组中返回.
代码
class Solution {
public:
vector<string> uncommonFromSentences(string s1, string s2) {
map<string, int> word;
cutSentence(s1, word);
cutSentence(s2, word);
vector<string> res;
for (map<string, int>::iterator it = word.begin();it != word.end();it++){
if (it->second == 1){
res.push_back(it->first);
}
}
return res;
}
void cutSentence(string input, map<string, int>& words){
istringstream ss(input);
string word;
while(ss>>word) {
if (words.find(word) == words.end()) {
words[word] = 1;
} else {
words[word]++;
}
}
}
};