884. Uncommon Words from Two Sentences
题目
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 <= 200
0 <= B.length <= 200
A
andB
both contain only spaces and lowercase letters.
解决
根据空格将两个字符串进行单词的划分,再从这些单词中找出仅出现一次的word
。
A
的长度为a
,B
的长度为b
,总单词数为n
1.人工分割字符串+unordered_map
- 时间复杂度:O(a + b)
- 空间复杂度:O(n)
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
vector<string> result;
// 记录单词以及出现的次数
unordered_map<string, int> words;
int lena = A.length();
int lenb = B.length();
int temp = 0;
// 分割字符串A
for (int i = 0; i < lena; i++) {
if (A[i] == ' ') {
string word = A.substr(temp, i - temp);
temp = i + 1;
(words.find(word) == words.end()) ? (words[word] = 1) : words[word]++;
}
if (i == lena - 1) {
string word = A.substr(temp, i - temp + 1);
temp = i + 1;
(words.find(word) == words.end()) ? (words[word] = 1) : words[word]++;
}
}
temp = 0;
// 分割字符串B
for (int i = 0; i < lenb; i++) {
if (B[i] == ' ') {
string word = B.substr(temp, i - temp);
temp = i + 1;
(words.find(word) == words.end()) ? (words[word] = 1) : words[word]++;
}
if (i == lenb - 1) {
string word = B.substr(temp, i - temp + 1);
temp = i + 1;
(words.find(word) == words.end()) ? (words[word] = 1) : words[word]++;
}
}
// 找只出现一次的word
for (unordered_map<string, int>::iterator it = words.begin(); it != words.end(); it++) {
if (it->second == 1) result.push_back(it->first);
}
return result;
}
};
2.istringstream+unordered_map
利用istringstream
可以实现字符串根据空格分割的功能,类似split()
函数。
- 时间复杂度:O(a + b)
- 空间复杂度:O(n)
class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
vector<string> result;
istringstream ss(A + " " + B);
unordered_map<string, int> words;
// 从ss中提取出来的东西类型为string
string temp;
// 从ss中提取单词
while (ss >> temp) {
words[temp]++;
}
for (auto word : words) {
if (word.second == 1) {
result.push_back(word.first);
}
}
return result;
}
};