884. 两句话中的不常见单词
给定两个句子
A
和B
。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。
您可以按任何顺序返回列表。
示例 1:
输入:A = "this apple is sweet", B = "this apple is sour" 输出:["sweet","sour"]
示例 2:
输入:A = "apple apple", B = "banana" 输出:["banana"]
提示:
0 <= A.length <= 200
0 <= B.length <= 200
A
和B
都只包含空格和小写字母。
解法一
//时间复杂度O(n), 空间复杂度O(n)
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
unordered_map<string, int> um;
istringstream iss(A + ' ' + B);
while(!iss.eof()) {
string str;
iss >> str;
um[str]++;
}
vector<string> res;
for(auto p : um) {
if(p.second == 1 && !p.first.empty()) res.push_back(p.first);
}
return res;
}
};
解法二
class Solution {
public:
void countStr(unordered_map<string, int>& um, string& str) {
string s = "";
for(char c : str) {
if(c != ' ') s += c;
else {
if(s != "") um[s]++;
s = "";
}
}
if(s != "") um[s]++;
}
vector<string> uncommonFromSentences(string A, string B) {
int n1 = A.size(), n2 = B.size();
unordered_map<string, int> um;
countStr(um, A);
countStr(um, B);
vector<string> res;
for(auto p : um) {
if(p.second == 1) res.push_back(p.first);
}
return res;
}
};
使用哈希表对两个句子中的单词计数,然后遍历哈希表,找出出现次数为1的单词,返回。
解法一使用了istringstream(16ms,可能是因为A + ' ' + B这一步,字符串拼接比较耗时);
解法二直接遍历字符(8ms)。
2019/07/25 17:15
来源:CSDN
作者:wanghy1995
链接:https://blog.csdn.net/sinat_27953939/article/details/103784798