← Coding round practice

Isomorphic Strings

MediumStrings

The problem

Two strings are isomorphic if characters in one can be consistently replaced to get the other (a one-to-one mapping in both directions).

Sample input

s = "egg", t = "add"

Sample output

true
Show the solution · 8 languages
fun isIsomorphic(s: String, t: String): Boolean {
    if (s.length != t.length) return false
    val mapST = HashMap<Char, Char>()
    val mapTS = HashMap<Char, Char>()
    for (i in s.indices) {
        val a = s[i]
        val b = t[i]
        if (mapST[a] != null && mapST[a] != b) return false
        if (mapTS[b] != null && mapTS[b] != a) return false
        mapST[a] = b
        mapTS[b] = a
    }
    return true
}

fun main() {
    println(isIsomorphic("egg", "add"))
}