2531. Make Number of Distinct Characters Equal

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
class Solution {
public boolean isItPossible(String word1, String word2) {
Map<Character, Integer> countMap1 = new HashMap<>();
Map<Character, Integer> countMap2 = new HashMap<>();

for (int i = 0; i < word1.length(); i++) {
char c = word1.charAt(i);
countMap1.merge(c, 1, Integer::sum);
}
for (int i = 0; i < word2.length(); i++) {
char c = word2.charAt(i);
countMap2.merge(c, 1, Integer::sum);
}

for (Map.Entry<Character, Integer> entry1 : countMap1.entrySet()) {
char c1 = entry1.getKey();
int count1 = entry1.getValue();
for (Map.Entry<Character, Integer> entry2 : countMap2.entrySet()) {
char c2 = entry2.getKey();
int count2 = entry2.getValue();

if (c1 == c2) {
// 两个字符相同,若两个字符串的不同字符数相等,则可交换 c1 与 c2
if (countMap1.size() == countMap2.size()) {
return true;
}
} else {
// 两个字符不相同,此时尝试交换 c1 与 c2
if (countMap1.size() - (count1 == 1 ? 1 : 0) + (!countMap1.containsKey(c2) ? 1 : 0) ==
countMap2.size() - (count2 == 1 ? 1 : 0) + (!countMap2.containsKey(c1) ? 1 : 0)) {
return true;
}
}
}
}

return false;
}
}

关键点在于比较交换后的两个字符串中的不同字符数是否相等。

References

2531. Make Number of Distinct Characters Equal