LeetCode:2085.统计出现过一次的公共字符串
题目:
给你两个字符串数组words1
和words2
,请你返回在两个字符串数组中都恰好出现一次的字符串的数目。
示例1:
输入:words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
输出:2
解释:
- "leetcode" 在两个数组中都恰好出现一次,计入答案。
- "amazing" 在两个数组中都恰好出现一次,计入答案。
- "is" 在两个数组中都出现过,但在 words1 中出现了 2 次,不计入答案。
- "as" 在 words1 中出现了一次,但是在 words2 中没有出现过,不计入答案。
所以,有 2 个字符串在两个数组中都恰好出现了一次。
示例2:
输入:words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
输出:0
解释:没有字符串在两个数组中都恰好出现一次。
示例3:
输入:words1 = ["a","ab"], words2 = ["a","a","a","ab"]
输出:1
解释:唯一在两个数组中都出现一次的字符串是 "ab" 。
提示:
1 <= words1.length, words2.length <= 1000
1 <= words1[i].length, words2[j].length <= 30
words1[i]
和words2[j]
都只包含小写英文字母。
思路:
- 使用一个
map
数据结构来记录每个字符串在两个数组中出现的次数。 - 遍历
words1
数组,对每个字符串进行计数,记录在map
中。 - 遍历
words2
数组,对每个字符串进行计数,但为了区分这是在words2
中出现,将计数值加上一个较大的数(这里使用了1000
)。 - 最后,遍历
map
,找出计数值为1001
的字符串数量,即在两个数组中都恰好出现一次的字符串数量。
注意:如果某个字符串在 words1
数组中没有出现过,那么在 map
中它对应的键的值默认为 0
,因为在 C++ 中,如果 map
中不存在某个键,对该键进行访问时会自动创建该键,并将值初始化为对应值类型的默认值。
代码(C++):
class Solution {
public:
int countWords(vector<string>& words1, vector<string>& words2) {
map<string,int> record;
for (int i = 0; i < words1.size(); ++i) {
record[words1[i]]++;
}
for (int i = 0; i < words2.size(); ++i) {
record[words2[i]] += 1000;
}
int count = 0;
for(map<string,int>::iterator it = record.begin();it!=record.end();it++){
if (it->second==1001){
count++;
}
}
return count;
}
};