LeetCode 205: Isomorphic Strings

link

Two strings are isomorphic if we can find a two-way mapping between their characters that makes the two strings identical. We keep two maps to validate the two-way mapping.

Two maps we maintain are: s -> t and t -> s. For s[i] and t[i], either they have not been mapped yet or s[i] has been mapped to t[i] and t[i] has been mapped to s[i].

Time: \mathcal{O}(n), space: \mathcal{O}(n).

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s_t_map, t_s_map = {}, {}
        for a, b in zip(s, t):
            if (a not in s_t_map) != (b not in t_s_map):
                return False
             
            if a not in s_t_map:
                s_t_map[a] = b
                t_s_map[b] = a
                continue
             
            if s_t_map[a] != b or t_s_map[b] != a:
                return False
         
        return True

Leave a comment