Python 52ms


  • 0
    M

    In this problem, it is easy to think of use dictionary to save the mapped key and value. And we need to pay attention to one rule:
    (1) No two characters may map to the same character but a character may map to itself. Which means the same values can not appear twice, eg. "aa" "ba" is False.
    The time complexity is O(n), and the space complexity is O(n)

        def isIsomorphic(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            #s="egg"
            #t="add"
            if len(s)!=len(t):
                return False
            
            replaces ={} #save that "e":"a", if the next time is different then it is False
            
            for i,j in zip(s,t):
         
                linked = replaces.get(i, '') #the key is the smaller one
                if len(linked)==0:
                    if j in replaces.values(): #value already existed
                        return False
                    replaces[i] = j
                else:
                    if linked!=j: #not mapping the value found
                        return False            
                    
            return True

Log in to reply
 

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