题目: 给定两个字符串 s 和 t,判断它们是否是同构的。如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
示例:
示例 1:
输入: s = "egg", t = "add"
输出: true
示例 2:
输入: s = "foo", t = "bar"
输出: false
示例 3:
输入: s = "paper", t = "title"
输出: true
说明: 你可以假设 s 和 t 具有相同的长度。
代码:
classSolution:defisIsomorphic(self, s:str, t:str)->bool:
s,s2 =list(s),list(s)
t,t2 =list(t),list(t)
result ={}
a = b =0for i inrange(len(s)):if s[i]notin result:
result[s[i]]=t[i]
s[i]= result[s[i]]if s == t:
a =1
result ={}for i inrange(len(s)):if t2[i]notin result:
result[t2[i]]=s2[i]
t2[i]= result[t2[i]]if s2 == t2:
b =1if a == b ==1:returnTruereturnFalse# 执行用时 :44 ms, 在所有 python3 提交中击败了97.57%的用户# 内存消耗 :14.9 MB, 在所有 python3 提交中击败了5.30%的用户