LeetCode in Kotlin

127. Word Ladder

Hard

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

Example 1:

Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]

Output: 5

Explanation: One shortest transformation sequence is “hit” -> “hot” -> “dot” -> “dog” -> cog”, which is 5 words long.

Example 2:

Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”]

Output: 0

Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.

Constraints:

Solution

class Solution {
    fun ladderLength(beginWord: String, endWord: String, wordDict: List<String>): Int {
        var beginSet: MutableSet<String> = HashSet()
        var endSet: MutableSet<String> = HashSet()
        val wordSet: Set<String> = HashSet(wordDict)
        val visited: MutableSet<String> = HashSet()
        if (!wordDict.contains(endWord)) {
            return 0
        }
        var len = 1
        val strLen = beginWord.length
        beginSet.add(beginWord)
        endSet.add(endWord)
        while (beginSet.isNotEmpty() && endSet.isNotEmpty()) {
            if (beginSet.size > endSet.size) {
                val temp = beginSet
                beginSet = endSet
                endSet = temp
            }
            val tempSet: MutableSet<String> = 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
    }
}