How to check Isomorphic Strings?

[Question]: Given two strings s and tdetermine if they are isomorphic.

Definition: Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false
// TC: O(N)
// SC: O(N)
func isIsomorphic(_ s: String, _ t: String) -> Bool {
    var rightDic = [Character:String.Index](), leftDic = rightDic
    for i in s.indices {
        guard rightDic[s[i]] == leftDic[t[i]] else { return false }
        rightDic[s[i]] = i
        leftDic[t[i]] = i
    return true

let iso1 = "egg"
let iso2 = "add"
let isISO = isIsomorphic(iso1, iso2)
print("isISO--- ", isISO) // true

Leave a Comment

Your email address will not be published. Required fields are marked *