O(n) python solution using hashmap and set


  • 0
    A

    class Solution(object):

    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        history = {}
        used_chars = set()
        if len(s) != len(t):
            return False
        
        for i in range(len(s)):
            if s[i] not in history:
                if t[i] in used_chars:
                    return False
                history[s[i]] = t[i]
                used_chars.add(t[i])
            elif history[s[i]] != t[i]:
                return False
        return True
    

    hashmap is used to keep history of which 's' char is assigned which 't' char and set is used to verify we are not assigning the same character twice.


Log in to reply
 

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