gpt4 book ai didi

python - 同构python算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:42 25 4
gpt4 key购买 nike

问题:给定两个字符串 s 和 t,判断它们是否同构。

如果s中的字符可以被替换为t,则两个字符串是同构的。

所有出现的字符都必须替换为另一个字符,同时保留字符的顺序。没有两个字符可以映射到同一个字符,但一个字符可以映射到它自己。

我的代码:

def isIsomorphic(self, s, t):
# write your code here
remap = dict()
if s == t:
return True
if len(s) != len(t):
return False
for i in range(len(s)):
if s[i] not in remap.keys() and t[i] in remap.values():
return False
elif s[i] not in remap.keys():
remap[s[i]] = t[i]
else:
if remap[s[i]] != t[i]:
return False
return True

错误提示: 您的代码运行时间超出了我们的预期。检查你的时间复杂度。如果您的时间复杂度最好,则超出时间限制通常是由无限循环引起的。

请问我如何改进我的代码

最佳答案

如果每个字符串中唯一字符的数量与它们之间对应字符的唯一对的数量相同(它们的长度也必须相同),则字符串将是同构的。

所以这个函数会简洁且更快地完成:

def isIsomorphic(w1,w2) : 
if len(w1) != len(w2): return False
return len(set(w1)) == len(set(w2)) == len(set(zip(w1,w2)))

[编辑] 在我的计算机上,一对 25 个字符串的 100 万次迭代需要 3.3 秒(相比之下,Aran-Fey 的更新代码需要 12 秒)。

关于python - 同构python算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49679872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com