leetcode-205-同构字符串

题目描述:

 第一次提交:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        dicA = {}
        dicB = {}
        for i in range(len(s)):
            if s[i] not in dicA:
                dicA[s[i]] = t[i]
            else:
                if dicA[s[i]]!=t[i]:
                    return False
        for i in range(len(s)):
            if t[i] not in dicB:
                dicB[t[i]] = s[i]
            else:
                if dicB[t[i]]!=s[i]:
                    return False
        return True

优化:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        hash = {}
        for i, c in enumerate(s):
            if hash.get(c):
                if t[i] != hash[c]:
                    return False
            else:
                if t[i] in hash.values():
                    return False
                hash[c] = t[i]
        return True

方法二:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        return [*map(s.index, s)] == [*map(t.index, t)]

猜你喜欢

转载自www.cnblogs.com/oldby/p/11617055.html