给你两个字符串数组 words1 和 words2 ,请你返回在两个字符串数组中 都恰好出现一次 的字符串的数目。
输入:words1 = [“leetcode”,“is”,“amazing”,“as”,“is”], words2 = [“amazing”,“leetcode”,“is”]
输出:2
解释:
1
<
=
w
o
r
d
s
1.
l
e
n
g
t
h
,
w
o
r
d
s
2.
l
e
n
g
t
h
<
=
1000
1 <= words1.length, words2.length <= 1000
1<=words1.length,words2.length<=1000
1
<
=
w
o
r
d
s
1
[
i
]
.
l
e
n
g
t
h
,
w
o
r
d
s
2
[
j
]
.
l
e
n
g
t
h
<
=
30
1 <= words1[i].length, words2[j].length <= 30
1<=words1[i].length,words2[j].length<=30
w
o
r
d
s
1
[
i
]
words1[i]
words1[i] 和
w
o
r
d
s
2
[
j
]
words2[j]
words2[j] 都只包含小写英文字母。
mp1
来统计word1
中每个字符串的出现次数mp2
来统计word2
中每个字符串的出现次数mp1
,判断它在word1,word2
中的出现次数是否都是1
,如果都是1
的话,记录答案word1
里所有字符串的长度和,
m
m
m为word2
里所有字符串的长度和func countWords(words1 []string, words2 []string) int {
mp1 := make(map[string]int, len(words1))
mp2 := make(map[string]int, len(words2))
for _, word := range words1 {
mp1[word]++
}
for _, word := range words2 {
mp2[word]++
}
var ans = 0
for k, v := range mp1 {
if v != 1 {
continue
}
if cnt, ok := mp2[k]; ok && cnt == 1 {
ans++
}
}
return ans
}
class Solution {
public:
int countWords(vector<string>& words1, vector<string>& words2) {
map<string,int>mp1,mp2;
for(auto word:words1) {
mp1[word]++;
}
for(auto word:words2) {
mp2[word]++;
}
int ans = 0;
for(auto it:mp1) {
if (it.second == 1 && mp2[it.first] == 1) {
ans++;
}
}
return ans;
}
};
mp
来统计word1
中每个字符串的出现次数word2
的字符串word
,对mp[word]
的情况进行讨论
mp[word]=1
说明word
在word1
里出现了一次,更新答案,且将mp[word]
赋值为一个特殊的数字,这里赋值为-1
mp[word]=-1
说明word
在word2
里已经出现了一次,当前是第二次,更新答案(这里是ans--
,因为word
已经不符合条件了),且将mp[word]
赋值为正常的计数2
func countWords(words1 []string, words2 []string) int {
mp := make(map[string]int, len(words1))
for _, word := range words1 {
mp[word]++
}
var ans = 0
for _, word := range words2 {
switch mp[word] {
case 1:
ans++
mp[word] = -1
case -1:
ans--
mp[word] = 2
}
}
return ans
}
class Solution {
public:
int countWords(vector<string>& words1, vector<string>& words2) {
map<string,int>mp;
for(auto word:words1) {
mp[word]++;
}
int ans = 0;
for(auto word:words2) {
if(mp[word]==1) {
mp[word] = -1;
ans ++;
} else if(mp[word]==-1) {
mp[word] = 2;
ans --;
}
}
return ans;
}
};