Star

LeetCode 127. Word Ladder

Question

Explanation

本题用DFS做会严重超时,用BFS也要注意一下替换的方式。其实用双边BFS会更快。

Code

Solution 1: BFS

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
55
56
57
58
59
60
61
public class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet<>();
for (String word : wordList) {
dict.add(word);
}
if (wordList == null) return 0;
if (beginWord.equals(endWord)) return 1;
// wordList.add(beginWord);
// wordList.add(endWord);
HashSet<String> hash = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
hash.add(beginWord);
int length = 1;
while(!queue.isEmpty()) {
length ++;
int size = queue.size();
for(int i=0; i<size; i++) {
String word = queue.poll();
for (String nextWord: getNextWords(word, dict)) {
if (hash.contains(nextWord)) {
continue;
}
if (nextWord.equals(endWord)) {
return length;
}
hash.add(nextWord);
queue.offer(nextWord);
}
}
}
return 0;
}
private List<String> getNextWords(String word, Set<String> wordList) {
List<String> nextWords = new ArrayList<>();
for (char c = 'a' ; c <'z'; c++) {
for (int i=0; i< word.length(); i++){
if (c == word.charAt(i)) {
continue;
}
String nextWord = replace(word, i, c);
if (wordList.contains(nextWord)) {
nextWords.add(nextWord);
}
}
}
return nextWords;
}
private String replace(String word, int i, char c) {
char[] chars = word.toCharArray();
chars[i] = c;
return new String(chars);
}
}