-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetcode_127_33.java
More file actions
42 lines (41 loc) · 1.37 KB
/
Leetcode_127_33.java
File metadata and controls
42 lines (41 loc) · 1.37 KB
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
/*
* @lc app=leetcode id=127 lang=java
*
* [127] Word Ladder
*/
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (!wordList.contains(endWord)) return 0;
int level = 1;
Set<String> set = new HashSet<>();
for(String word: wordList){
set.add(word);
}
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
String tmpWord = queue.poll();
char[] array = tmpWord.toCharArray();
for(int j = 0; j < array.length; j++){
char c = array[j];
for(char k = 'a'; k <= 'z'; k++){
array[j] = k;
String newWord = String.valueOf(array);
if(k != c &&set.contains(newWord)){
queue.offer(newWord);
set.remove(newWord);
if(newWord.equals(endWord)){
return ++level;
}
}
}
array[j] = c;
}
}
level++;
}
return 0;
}
}