g0801_0900.s0890_find_and_replace_pattern.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.s0890_find_and_replace_pattern
// #Medium #Array #String #Hash_Table #2023_04_10_Time_150_ms_(100.00%)_Space_35.9_MB_(11.11%)
class Solution {
fun findAndReplacePattern(words: Array, pattern: String): List {
val finalans: MutableList = ArrayList()
if (pattern.length == 1) {
finalans.addAll(words)
return finalans
}
for (word in words) {
val check = CharArray(26)
check.fill('1')
val ans: HashMap = HashMap()
for (j in word.indices) {
val pat = pattern[j]
val wor = word[j]
if (ans.containsKey(pat)) {
if (ans[pat] == wor) {
if (j == word.length - 1) {
finalans.add(word)
}
} else {
break
}
} else {
if (j == word.length - 1 && check[wor.code - 'a'.code] == '1') {
finalans.add(word)
}
if (check[wor.code - 'a'.code] != '1' && check[wor.code - 'a'.code] != pat) {
break
}
if (check[wor.code - 'a'.code] == '1') {
ans[pat] = wor
check[wor.code - 'a'.code] = pat
}
}
}
}
return finalans
}
}