avatar

LeetCode-884 两句话中的不常见单词

📝题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
给定两个句子 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


📝思路

学习一下map的用法,算法方面没啥好说的。
🐣:STL强强强🤙

📝题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
vector<string> uncommonFromSentences(string A, string B) {
unordered_map<string, int> record;
int lenA = A.size(), lenB = B.size();
string temp = "";
for (int i = 0; i < lenA; ++i){
if (A[i] == ' '){
auto iter = record.find(temp);
if (iter != record.end()) ++iter->second;
else record.insert(pair<string, int>(temp, 1));
temp = "";
}
else
temp += A[i];
}
auto iterator = record.find(temp);
if (iterator != record.end()) ++iterator->second;
else record.insert(pair<string, int>(temp, 1));
temp = "";

for (int i = 0; i < lenB; ++i){
if (B[i] == ' '){
auto iter = record.find(temp);
if (iter != record.end()) ++iter->second;
else record.insert(pair<string, int>(temp, 1));
temp = "";
}
else
temp += B[i];
}
iterator = record.find(temp);
if (iterator != record.end()) ++iterator->second;
else record.insert(pair<string, int>(temp, 1));
temp = "";

auto iter = record.begin();
vector<string> result;
for (; iter != record.end(); ++iter){
if (iter->second == 1) result.push_back(iter->first);
}
return result;
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2020/04/21/LeetCode-884-%E4%B8%A4%E5%8F%A5%E8%AF%9D%E4%B8%AD%E7%9A%84%E4%B8%8D%E5%B8%B8%E8%A7%81%E5%8D%95%E8%AF%8D/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.