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

g0801_0900.s0890_find_and_replace_pattern.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
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
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy