我的代码没有通过这个测试用例。有人可以帮助我了解什么是不正确的我的代码?
输入:"badc"baba"输出:真正的预期:假
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
if len(s)==0 or len(t)==0:
return False
for i in range(len(s)):
if s[i] in dict:
if dict[s[i]] != t[i]:
return False
else:
dict[s[i]] = t[i]
return True
如问题描述中所述:
没有两个字符可以映射到相同的字符
对于输入s = badc
和t = baba
,s
中的字母b
和d
都映射到t
中的字母b
,这违反了规则,应该返回false。
如我所提到的,我们可以在else子句中添加一个条件,以确保字典中的值是唯一的:
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
if len(s)==0 or len(t)==0:
return False
for i in range(len(s)):
if s[i] in dict:
if dict[s[i]] != t[i]:
return False
else:
if t[i] in dict.values():
return False
dict[s[i]] = t[i]
return True
您是否检查了1个字符串,即s
是否与t
同构?你还需要检查t
,即t
是否同构于s
?
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
dict2 = {}
if len(s)==0 or len(t)==0:
return False
if len(s)!= len(t):
return False
for a,b in zip(s,t):
if a not in dict:
dict[a]=b
else:
if dict[a]!=b:
return False
if b not in dict2:
dict2[b] = a
else:
if dict2[b]!=a:
return False
return True
下面是更python化的解决方案:
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return [s.index(ch) for ch in s] == [t.index(ch) for ch in t]
相当于:
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return [*map(s.index, s)] == [*map(t.index, t)]