题解方法
广度优先搜索
核心代码
广度优先搜索
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
| Queue<Pair<String, Integer>> queue = new ArrayDeque<>(); Set<String> visited = new HashSet<>();
queue.offer(new Pair<>(s1, 0)); visited.add(s1);
while (!queue.isEmpty()) { Pair<String, Integer> pair = queue.poll(); String cur = pair.getKey(); int step = pair.getValue();
if (cur.equals(s2)) { return step; }
int idx = 0; while (cur.charAt(idx) == s2.charAt(idx)) { idx++; }
for (int i = idx + 1; i < len; i++) { if (cur.charAt(i) == s2.charAt(i)) { continue; } if (cur.charAt(i) == s2.charAt(idx)) { String next = swap(cur, idx, i); if (!visited.contains(next)) { queue.offer(new Pair<>(next, step + 1)); visited.add(next); } } } }
|
题目来源
854. 相似度为 K 的字符串 - 力扣(LeetCode)