forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
54 lines (51 loc) · 1.87 KB
/
Solution.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
package g0101_0200.s0127_word_ladder;
// #Hard #Top_Interview_Questions #String #Hash_Table #Breadth_First_Search
// #Graph_Theory_I_Day_12_Breadth_First_Search
// #2022_06_23_Time_37_ms_(94.58%)_Space_54.1_MB_(66.08%)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordDict) {
Set<String> beginSet = new HashSet<>();
Set<String> endSet = new HashSet<>();
Set<String> wordSet = new HashSet<>(wordDict);
Set<String> visited = new HashSet<>();
if (!wordDict.contains(endWord)) {
return 0;
}
int len = 1;
int strLen = beginWord.length();
beginSet.add(beginWord);
endSet.add(endWord);
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
if (beginSet.size() > endSet.size()) {
Set<String> temp = beginSet;
beginSet = endSet;
endSet = temp;
}
Set<String> tempSet = new HashSet<>();
for (String s : beginSet) {
char[] chars = s.toCharArray();
for (int i = 0; i < strLen; i++) {
char old = chars[i];
for (char j = 'a'; j <= 'z'; j++) {
chars[i] = j;
String temp = new String(chars);
if (endSet.contains(temp)) {
return len + 1;
}
if (!visited.contains(temp) && wordSet.contains(temp)) {
tempSet.add(temp);
visited.add(temp);
}
}
chars[i] = old;
}
}
beginSet = tempSet;
len++;
}
return 0;
}
}