【leetcode】205. 同构字符串

给定两个字符串 和 t,判断它们是否是同构的。

如果 中的字符可以被替换得到 ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

示例 1:

输入: s ="egg",t = "add"
输出: true
说明:你可以假设 s 和 t 具有相同的长度。

解答:

# -*- coding:utf-8 -*-
class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if(len(s) != len(t)):
            return False
        else:
            dictionary = list(zip(s,t))
            # print(dictionary)
            # temp = set(dictionary)
            # print(temp)
            sDict = {}
            tDict = {}
            for i,j in dictionary:
                if i not in sDict:
                    sDict[i] = j
                if j not in tDict:
                    tDict[j] = i
                if(sDict[i] != j or tDict[j] != i ):
                    return False
            return True



def main():
    s = "paper"
    t = "title"
    myresult = Solution()
    print(myresult.isIsomorphic(s,t))


if __name__ == '__main__':
    main()



'''
l = ['a', 'b', 'c', 'd', 'e','f']
print(l)
print(l[:-1]) # ['a', 'b', 'c', 'd', 'e']
print(l[1:]) # ['b', 'c', 'd', 'e', 'f']
#打印列表
print(list(zip(l[:-1],l[1:])))
# [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f')]
'''

别人写的一行代码搞定:

 return len(set(zip(s,t))) == len(set(s)) == len(set(t)) 

知识点补充:

以下实例展示了 zip 的使用方法:

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式[(1, 2, 3), (4, 5, 6)]

列表元素依次相连:

l = ['a', 'b', 'c', 'd', 'e','f']
print(l)
print(l[:-1]) # ['a', 'b', 'c', 'd', 'e']
print(l[1:]) # ['b', 'c', 'd', 'e', 'f']
#打印列表
print(list(zip(l[:-1],l[1:])))
# [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f')]

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值