思路:
先记录同一个值出现的次数,再将字典中的值取出,比较2个列表即可
代码:
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
dit1=dict()
dit2=dict()
for i in range(len(s)):
if s[i] not in dit1:
dit1[s[i]]=i
continue
#记录其他下标
dit1[s[i]]+=i
for j in range(len(t)):
if t[j] not in dit2:
dit2[t[j]]=j
continue
#记录其他下标
dit2[t[j]]+=j
ret1=list(dit1.values())
ret2=list(dit2.values())
if ret1==ret2:
return True
return False
还有高手?思路差不多,更精简
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
#记录值的出现次数
dicts = Counter(s)
dictt = Counter(t)
if list(dicts.values()) != list(dictt.values()):
return False
for i in range(len(s)):
inds = list(dicts.keys()).index(s[i])
if list(dictt.keys())[inds] != t[i]:
return False
return True