给定两个字符串 s 和 t,判断它们是否是同构的。
如果 s 中的字符可以被替换得到 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')]