My python solution


  • 0
    M
    class Solution(object):
        def isIsomorphic(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            if s == t == "":
                return True
            
            compare = {}
            for i in range(len(s)):
                if s[i] not in compare: 
                    if t[i] in compare.values():
                        return False
                    compare[s[i]] = t[i]
                else:
                    if compare[s[i]] != t[i]:
                        return False
           
            return True
    

    So I use a dictionary to check if they are isomorphic.

    for example, I have s = 'egh', t = 'add'.

    The step of for loop:

    1. dictionary will be: {'e':'a'}

    2. dictionary will be: {'e':'a', 'g':'d'}

    3. when it tries to insert {'h':'d'}, my code will found that 'd' has been used before and return False.

    It is the same meaning when s = 'egg', t = 'adh'.

    On the third step of the for loop, my code will find that g have been used before but with different value and return False.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.