-
Notifications
You must be signed in to change notification settings - Fork 2
/
WordLadder.java
72 lines (58 loc) · 1.61 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.touir.leetcode.solutions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import com.touir.leetcode.Solution;
public class WordLadder extends Solution {
/**
* problem: 127. Word Ladder
*
* url: https://leetcode.com/problems/word-ladder/
*/
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (!wordList.contains(endWord))
return 0;
Queue<String> queue = new LinkedList<String>();
Set<String> words = new HashSet<String>(wordList), visited = new HashSet<String>();
queue.add(beginWord);
visited.add(beginWord);
int queueSize, level = 1;
String word, str;
char[] w;
while (!queue.isEmpty()) {
queueSize = queue.size();
while (queueSize-- > 0) {
word = queue.poll();
if (word.equals(endWord))
return level;
w = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
for (char c = 'a'; c <= 'z'; c++) {
if (c == word.charAt(i))
continue;
w[i] = c;
str = new String(w);
if (!visited.contains(str) && words.contains(str)) {
queue.add(str);
visited.add(str);
}
}
w[i] = word.charAt(i);
}
}
level++;
}
return 0;
}
@Override
public void test() {
System.out.println(
"result: " + this.ladderLength("hit", "cog", Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"))
+ ", expected: 5");
System.out.println("result: "
+ this.ladderLength("hit", "cog", Arrays.asList("hot", "dot", "dog", "lot", "log")) + ", expected: 0");
}
}