-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_127.java
38 lines (37 loc) · 1.49 KB
/
LC_127.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
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class LC_127 {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashSet<String> wordSet = new HashSet<>(wordList);
HashSet<String> visited = new HashSet<>();
Deque<String> que = new LinkedList<>();
if (!wordSet.contains(endWord)) return 0;
if (beginWord.equals(endWord)) return 1;
que.addLast(beginWord);
visited.add(beginWord);
int len = 1;
while (!que.isEmpty()) {
int size = que.size();
len++;
while (size-- > 0) {
String curStr = que.removeFirst();
for (int i = 0; i < curStr.length(); i++) {
for (int j = 0; j < 26; j++) {
if (curStr.charAt(i) != (char) ('a' + j)) {
StringBuilder sb = new StringBuilder(curStr);
sb.setCharAt(i, (char) ('a' + j));
if (!visited.contains(sb.toString()) && wordSet.contains(sb.toString())) {
if (sb.toString().equals(endWord)) return len;
visited.add(sb.toString());
que.addLast(sb.toString());
}
}
}
}
}
}
return 0;
}
}