-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode127 - Word Ladder
48 lines (47 loc) · 1.52 KB
/
Leetcode127 - Word Ladder
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
//展示代码 - BFS 和 code style
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>();
for(String aWord: wordList) {
wordSet.add(aWord);
}
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
int distance = 1;
while (!queue.isEmpty() && !wordSet.isEmpty()) {
Queue<String> queue2 = new LinkedList<>();
distance++;
while (!queue.isEmpty()) {
String top = queue.poll();
ArrayList<String> wordsWithinDistance =
getWordsWithinDistance(wordSet, top);
if (wordsWithinDistance.contains(endWord)) {
return distance;
}
queue2.addAll(wordsWithinDistance);
}
queue = queue2;
}
return 0;
}
public ArrayList<String> getWordsWithinDistance(Set<String> wordSet, String word) {
ArrayList<String> results = new ArrayList<>();
char[] wordCharArr = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
char oriChar = wordCharArr[i];
for (char c = 'a'; c <= 'z'; c++) {
if (c == oriChar) {
continue;
}
wordCharArr[i] = c;
String newStr = new String(wordCharArr);
if (wordSet.contains(newStr)) {
results.add(newStr);
wordSet.remove(newStr);
}
}
wordCharArr[i] = oriChar;
}
return results;
}
}