Minimum Genetic Mutation LeetCode solution in Java

1
class Solution {
2
public int minMutation(String start, String end, String[] bank) {
3
Set<String> set = new HashSet<>();
4
for (String tmp : bank) {
5
set.add(tmp);
6
}
7
if (!set.contains(end)) return -1;
8
if (start.equals(end)) return 0;
9
char[] var = {'A', 'C', 'G', 'T'};
10
Queue<String> q = new LinkedList<>();
11
q.add(start);
12
int count = 0;
13
while (!q.isEmpty()) {
14
int size = q.size();
15
for (int i = 0; i < size; i++) {
16
String str = q.poll();
17
char[] tmp = str.toCharArray();
18
if (str.equals(end)) return count;
19
for (int j = 0; j < 8; j++) {
20
char ch = tmp[j];
21
for (int k = 0; k < 4; k++) {
22
tmp[j] = var[k];
23
String node = new String(tmp);
24
if (set.contains(node)) {
25
q.add(node);
26
set.remove(node);
27
}
28
}
29
tmp[j] = ch;
30
}
31
}
32
count++;
33
}
34
return -1;
35
}
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0