All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0966_vowel_spellchecker.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
package g0901_1000.s0966_vowel_spellchecker

// #Medium #Array #String #Hash_Table #2023_05_05_Time_371_ms_(100.00%)_Space_77.8_MB_(50.00%)

class Solution {
    private var matched: HashSet? = null
    private var capitalizations: HashMap? = null
    private var vowelErrors: HashMap? = 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, queries: Array): Array {
        val answer = arrayOfNulls(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
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy