LeetCode75-1657-Close-Two-String

🧠 思路总结

判断两个字符串是否 close:

  1. 长度是否相同
  2. 是否包含完全相同的字母集合
  3. 字母出现次数是否只是一个排列

需要找什么可以一直不变

  • Operation 1: Swap any two existing characters.
    For example, abcde -> aecdb。本质上是需要确保word1中有的charword2中也得有
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aacabb -> bbcbaa (all a’s turn into b’s, and all b’s turn into a’s)。本质上是需要确保word1中有的charword2中也得有 并且 需要确保occurrence排序后一模一样

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) {
return false;
}
Map<Character, Integer> m1 = new HashMap<>();
Map<Character, Integer> m2 = new HashMap<>();
for (char c : word1.toCharArray()) {
m1.put(c, m1.getOrDefault(c, 0) + 1);
}
for (char c : word2.toCharArray()) {
m2.put(c, m2.getOrDefault(c, 0) + 1);
}
if (!m1.keySet().equals(m2.keySet())) {
return false;
}
List<Integer> occ1 = new ArrayList<>(m1.values());
List<Integer> occ2 = new ArrayList<>(m2.values());
Collections.sort(occ1);
Collections.sort(occ2);
return occ1.equals(occ2);
}
}

LeetCode75-1657-Close-Two-String
https://powersixxx.github.io/leetcode-blog/2026/02/06/LeetCode75-1657-Close-Two-String/
作者
Baowen Liu
发布于
2026年2月6日
许可协议