leetcode205:同构字符串

思想:

定义一个空字典reserve,先判断s[i]是否再字典键中,若不在则继续判断t[i]是否在字典值中,若不在则赋值,若在则返回False。若在则判断值是否相等,相等则继续,反之则返回False。

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

当小菜鸟自己写出来的时候还是蛮开心的,然后大佬的方法总是打脸。。。。

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return len(set(s)) == len(set(t)) == len(set(zip(s, t)))

大佬的思想:

将set(t)后算长度(去重),set(s)后算长度,zip(s,t)将s和t两两对应位置打包成元祖在组合成列表,然后在set()之后算长度。只有三个长度都相等的时候s和t才是同构字符串。

知识点:

1.zip()

a = [1,2,3]

b = [4,5,6]

zipped = zip(a,b) #打包为元组的列表

[(1, 4), (2, 5), (3, 6)]

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/83789717