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 <= 2000 <= B.length <= 200AandBboth contain only spaces and lowercase letters.
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
unordered_map<string, int> maps;
vector<string> result;
getToken(maps, A);
getToken(maps, B);
for(unordered_map<string, int>::iterator it = maps.begin();it!=maps.end();++it)
{
if(it->second == 1)
result.push_back(it->first);
}
return result;
}
void getToken(unordered_map<string, int>& maps, string des)
{
int before = 0, end = 0;
while(end < des.size())
{
if(des[end]!=' ')
{
++end;
continue;
}
else
{
string temp = des.substr(before, end - before);
maps[temp]+=1;
before = ++end;
}
}
if(before < end)
{
string temp = des.substr(before, end - before);
maps[temp]+=1;
}
}
};
本文介绍了一种从两句话中提取独特词汇的算法,通过使用哈希映射记录每个单词出现的次数,筛选出只在一句中出现一次的词汇。示例展示了如何处理不同输入情况,包括重复单词和完全不同的句子。
409

被折叠的 条评论
为什么被折叠?



