g0101_0200.s0127_word_ladder.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0127_word_ladder
// #Hard #Top_Interview_Questions #String #Hash_Table #Breadth_First_Search
// #Graph_Theory_I_Day_12_Breadth_First_Search
// #2022_10_08_Time_396_ms_(98.68%)_Space_49.1_MB_(80.26%)
class Solution {
fun ladderLength(beginWord: String, endWord: String, wordDict: List): Int {
var beginSet: MutableSet = HashSet()
var endSet: MutableSet = HashSet()
val wordSet: Set = HashSet(wordDict)
val visited: MutableSet = HashSet()
if (!wordDict.contains(endWord)) {
return 0
}
var len = 1
val strLen = beginWord.length
beginSet.add(beginWord)
endSet.add(endWord)
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
if (beginSet.size > endSet.size) {
val temp = beginSet
beginSet = endSet
endSet = temp
}
val tempSet: MutableSet = HashSet()
for (s in beginSet) {
val chars = s.toCharArray()
for (i in 0 until strLen) {
val old = chars[i]
var j = 'a'
while (j <= 'z') {
chars[i] = j
val temp = String(chars)
if (endSet.contains(temp)) {
return len + 1
}
if (!visited.contains(temp) && wordSet.contains(temp)) {
tempSet.add(temp)
visited.add(temp)
}
j++
}
chars[i] = old
}
}
beginSet = tempSet
len++
}
return 0
}
}