forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0127-word-ladder.kt
52 lines (41 loc) · 1.25 KB
/
0127-word-ladder.kt
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
class Solution {
fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int {
val set = wordList.toMutableSet()
if (!set.contains(endWord))
return 0
val queue = LinkedList<String>()
queue.add(beginWord)
set.remove(beginWord)
var step = 0
while(queue.size != 0) {
val size = queue.size
step++;
for (i in 0..size-1) {
val curr = queue.poll()
if (endWord.equals(curr))
return step
val neighbors = getNeighbors(curr, set)
for (neig in neighbors) {
queue.add(neig)
set.remove(neig)
}
}
}
return 0
}
fun getNeighbors(str: String, set: Set<String>): List<String> {
val res = ArrayList<String>()
val chars = str.toCharArray()
for (i in 0..chars.size-1) {
val temp = chars[i];
for (j in 'a'..'z') {
chars[i] = j
val newStr = String(chars)
if (set.contains(newStr))
res.add(newStr)
}
chars[i] = temp
}
return res
}
}