-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordLadder.java
47 lines (43 loc) · 1.39 KB
/
WordLadder.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
import java.util.*;
public class WordLadder {
public static void main(String[] args) {
WordLadder test = new WordLadder();
System.out.println(test.ladderLength("hot","dog",
Arrays.asList(new String[]{"hot","dog"})));
}
public int ladderLength(String start, String end, List<String> wordList) {
HashSet<String > dict = new HashSet<>(wordList);
// write your code here
if(!dict.contains(end)){
return 0;
}
int count =0;
Queue<String> words= new LinkedList<>();
words.add(start);
while(words.size()!=0){
count++;
int size = words.size();
while(size>0){
size--;
if(getAllValidWords(words.poll(),dict,words,end))
return count+1;
}
}
return 0;
}
public boolean getAllValidWords(String word, Set<String> dict,Queue<String> words, String end){
for (int i=0;i<word.length();i++){
StringBuilder sb = new StringBuilder(word);
for(char x='a';x<='z';x++){
sb.setCharAt(i,x);
String test = sb.toString();
if(dict.remove(test)){
if(test.equals(end))
return true;
words.add(sb.toString());
}
}
}
return false;
}
}