-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127Solution.java
49 lines (47 loc) · 1.42 KB
/
127Solution.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
// 127. Word Ladder
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> beginSet = new HashSet<>();
Set<String> endSet = new HashSet<>();
int count = 1;
Set<String> used = new HashSet<>();
beginSet.add(beginWord);
endSet.add(endWord);
Set<String> wordSet = new HashSet<>();
for(String s : wordList) {
wordSet.add(s);
}
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
// always start from the smaller set
if (beginSet.size() > endSet.size()) {
Set<String> set = beginSet;
beginSet = endSet;
endSet = set;
}
Set<String> temp = new HashSet<>();
for (String word: beginSet) {
char[] chs = word.toCharArray();
for (int i = 0; i < chs.length; i++) {
// construct the target word
for (char c = 'a'; c <= 'z'; c++) {
char old = chs[i];
chs[i] = c;
String target = String.valueOf(chs);
// find corresponding word
if (endSet.contains(target)) {
return count + 1;
}
// no, add it to next level
if (!used.contains(target) && wordSet.contains(target)) {
temp.add(target);
used.add(target);
}
//rollback
chs[i] = old;
}
}
}
beginSet = temp;
count++;
}
return 0;
}