leetcode-205-同构字符串

题目描述:

leetcode-205-同构字符串_第1张图片

 

 第一次提交:

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)]

leetcode-205-同构字符串_第2张图片

 

你可能感兴趣的:(leetcode-205-同构字符串)