Isomorphic Strings

Problem: Isomorphic Strings

To check whether 2 strings are isomorphic strings, we can get each letter from the source string. When a letter appears twice, if the second time it appears refer to the same letter as first time it refers to, then these two strings are OK. We use a hash table to hold the reference history of letters. Besides, we also need to avoid situation that several letters refer to the same letter. If this situation happens, the alphabet set of the string will be different.

Code in Python:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        hash_s = {}
        for i in xrange(len(s)):
            if s[i] not in hash_s:
                hash_s[s[i]] = t[i]
            else:
                if hash_s[s[i]] != t[i]:
                    return False

        s_set, t_set = set(s), set(t)
        if len(s_set) != len(t_set):
            return False

        return True

results matching ""

    No results matching ""