The solution to this problem is very easy but I struggled a little bit because I was focusing more on finding a regex to represent the pattern.
class Solution {
fun wordPattern(pattern: String, str: String): Boolean {
val map = HashMap<Char, String>()
val words = str.split(" ")
val unique = words.distinct()
if(pattern.length != words.size) return false
pattern.forEachIndexed { index, c ->
if(map.containsKey(c)){
if((map[c]!!) != words[index]) return false
}else map[c] = words[index]
}
return unique.size == map.size
}
}
Runtime: 172 ms, faster than 22.50% of Kotlin online submissions for Word Pattern.
Memory Usage: 33.5 MB, less than 100.00% of Kotlin online submissions for Word Pattern.