-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL127.java
More file actions
55 lines (53 loc) · 2.12 KB
/
L127.java
File metadata and controls
55 lines (53 loc) · 2.12 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class L127 {
/**
* 127. Word Ladder https://leetcode.com/problems/word-ladder/
*
* @timeComplexity n chars in word and N max transformation length in dictionary 26^n * N
* @spaceComplexity O(N)
*/
static class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet<>(wordList);
Map<String, Integer> levels = new HashMap<>();
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
levels.put(beginWord, 1);
while (!queue.isEmpty()) {
String cur = queue.poll();
// For each index in the string change char at that index and check if it is in dict
// If yes, add it to the queue
for (int i = 0; i < cur.length(); i++) {
for (char j = 'a'; j <= 'z'; j++) {
if (j == cur.charAt(i)) {
continue;
}
StringBuffer neighbour = new StringBuffer();
if (i > 0) {
neighbour.append(cur.substring(0, i));
}
neighbour.append(j);
if (i < cur.length()) {
neighbour.append(cur.substring(i + 1));
}
if (!dict.contains(neighbour.toString()) || levels.containsKey(neighbour.toString())) {
continue;
}
if (endWord.equals(neighbour.toString())) {
return levels.get(cur) + 1;
}
queue.add(neighbour.toString());
levels.put(neighbour.toString(), levels.get(cur) + 1);
}
}
}
return 0;
}
}
}