-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.java
54 lines (50 loc) · 1.58 KB
/
Solution2.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public int kSimilarity(String s1, String s2) {
PriorityQueue<Pair<Integer, String>> q
= new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));
q.offer(new Pair<>(f(s1, s2), s1));
Map<String, Integer> dist = new HashMap<>();
dist.put(s1, 0);
while (true) {
String s = q.poll().getValue();
if (s.equals(s2)) {
return dist.get(s);
}
for (String nxt : next(s, s2)) {
if (!dist.containsKey(nxt) || dist.get(nxt) > dist.get(s) + 1) {
dist.put(nxt, dist.get(s) + 1);
q.offer(new Pair<>(dist.get(nxt) + f(nxt, s2), nxt));
}
}
}
}
private int f(String s, String s2) {
int cnt = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) != s2.charAt(i)) {
++cnt;
}
}
return (cnt + 1) >> 1;
}
private List<String> next(String s, String s2) {
int i = 0, n = s.length();
char[] cs = s.toCharArray();
for (; cs[i] == s2.charAt(i); ++i) {
}
List<String> res = new ArrayList<>();
for (int j = i + 1; j < n; ++j) {
if (cs[j] == s2.charAt(i) && cs[j] != s2.charAt(j)) {
swap(cs, i, j);
res.add(new String(cs));
swap(cs, i, j);
}
}
return res;
}
private void swap(char[] cs, int i, int j) {
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
}
}