Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example, Given"egg","add", return true.

Given"foo","bar", return false.

Given"paper","title", return true.

Note: You may assume both s and t have the same length.

判断两个 String 是否同构:将 s 的每个字母替换成 t 中对应位置的字母,如果同一字母对应多个替换字母,则不是同构;同样要将 t 替换成 s,判断其是否存在一对多的对应。如果 s -> t 和 t -> s 中的字母替换都是一一对应,则 s 和 t 为同构。这里不能只用一个哈希表,因为要排除egg->ddd这种多对一的映射。

hashmapS[ t[i] ]=s[i]

hashmapT[ s[i] ]=t[i]

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        hashmapS,hashmapT = {}, {}
        for i in range(len(s)):
            if hashmapS.get(s[i]):
                if hashmapS[s[i]] != t[i]:
                    return False
            else:
                if hashmapT.get(t[i]):
                    return False
                hashmapS[s[i]] = t[i]
                hashmapT[t[i]] = s[i]
        return True
class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        hashmapS,hashmapT = {}, {}
        for i in range(len(s)):
            if hashmapS.get(s[i]):
                if hashmapS[s[i]] != t[i]:
                    return False
            else:
                hashmapS[s[i]] = t[i]

        for j in range(len(t)):
            if hashmapT.get(t[j]):
                if hashmapT[t[j]] != s[j]:
                    return False
            else:
                hashmapT[t[j]]=s[j]

        return True

Last updated

Was this helpful?