-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Ladder.java
More file actions
41 lines (27 loc) · 1.19 KB
/
Word_Ladder.java
File metadata and controls
41 lines (27 loc) · 1.19 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
public class Solution {
public int ladderLength(String start, String end, Set<String> dict) {
LinkedList<String> word = new LinkedList<String>();
LinkedList<Integer> num = new LinkedList<Integer>();
word.add(start);
num.add(1);
while(!word.isEmpty()){
String target = word.pop();
int index = num.pop();
if(target.equals(end)) return index;
char[] letter = target.toCharArray();
for(int i = 0;i < target.length();i++)
for(char c = 'a';c <= 'z';c++){
char tmp = letter[i];
letter[i] = c;
String new_word = new String(letter);
if(dict.contains(new_word)){
word.add(new_word);
num.add(index + 1);
dict.remove(new_word);
}
letter[i] = tmp;
}
}
return 0;
}
}