g0801_0900.s0819_most_common_word.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 g0801_0900.s0819_most_common_word
// #Easy #String #Hash_Table #Counting #2023_03_24_Time_211_ms_(83.33%)_Space_36.9_MB_(88.89%)
@Suppress("NAME_SHADOWING")
class Solution {
fun mostCommonWord(paragraph: String, banned: Array): String {
var paragraph = paragraph
paragraph = paragraph.replace("\\p{Punct}".toRegex(), " ").lowercase()
val a = paragraph.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in banned.indices) {
banned[i] = banned[i].lowercase()
}
val map: MutableMap = HashMap()
for (s in a) {
val x = map.getOrDefault(s, 0)
map[s] = x + 1
}
for (s in banned) {
map.remove(s)
map.remove("")
}
return map.maxBy { it.value }.key
}
}