My code is failing this testcase. Can someone please help me understand what is incorrect with my code?
Input: "badc" "baba" Output: true Expected: false
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
CodePudding user response:
As mentioned in the problem description:
No two characters may map to the same character
For input s = badc
and t = baba
, letter b
and d
in s
both map to letter b
in t
, which violated the rule and should return false.
As mentioned by bui, we can add a condition in the else clause, to make sure values in the dict are unique:
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
CodePudding user response:
you have checked that for 1 string only, ie is s
isomorphic to t
or not?
you need to check that also for t
, ie is t
isomorphic to s
or not?
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