LeetCode in Kotlin

966. Vowel Spellchecker

Medium

Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.

For a given query word, the spell checker handles two categories of spelling mistakes:

In addition, the spell checker operates under the following precedence rules:

Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].

Example 1:

Input: wordlist = [“KiTe”,”kite”,”hare”,”Hare”], queries = [“kite”,”Kite”,”KiTe”,”Hare”,”HARE”,”Hear”,”hear”,”keti”,”keet”,”keto”]

Output: [“kite”,”KiTe”,”KiTe”,”Hare”,”hare”,””,””,”KiTe”,””,”KiTe”]

Example 2:

Input: wordlist = [“yellow”], queries = [“YellOw”]

Output: [“yellow”]

Constraints:

Solution

class Solution {
    private var matched: HashSet<String>? = null
    private var capitalizations: HashMap<String, String>? = null
    private var vowelErrors: HashMap<String, String>? = null
    private fun isVowel(w: Char): Boolean {
        return w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u'
    }

    private fun removeVowels(word: String): String {
        val s = StringBuilder()
        for (w in word.toCharArray()) {
            s.append(if (isVowel(w)) '*' else w)
        }
        return s.toString()
    }

    private fun solveQuery(query: String): String? {
        if (matched!!.contains(query)) {
            return query
        }
        var word = query.lowercase()
        if (capitalizations!!.containsKey(word)) {
            return capitalizations!![word]
        }
        word = removeVowels(word)
        return if (vowelErrors!!.containsKey(word)) {
            vowelErrors!![word]
        } else ""
    }

    fun spellchecker(wordlist: Array<String>, queries: Array<String>): Array<String?> {
        val answer = arrayOfNulls<String>(queries.size)
        matched = HashSet()
        capitalizations = HashMap()
        vowelErrors = HashMap()
        for (word in wordlist) {
            matched!!.add(word)
            var s = word.lowercase()
            capitalizations!!.putIfAbsent(s, word)
            s = removeVowels(s)
            vowelErrors!!.putIfAbsent(s, word)
        }
        for (i in queries.indices) {
            answer[i] = solveQuery(queries[i])
        }
        return answer
    }
}