初始想法: 搞2个dict 分别储存每个str的第每个新出现字母第一次出现的位置 如果二者一直保持一致 则为True 代码如下
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: s_dict = {} t_dict = {} length = len(s) index = 1 for i in range(length): if (t[i] not in t_dict and s[i] in s_dict) or (t[i] in t_dict and s[i] not in s_dict): return False elif t[i] not in t_dict and s[i] not in s_dict: s_dict[s[i]] = index t_dict[t[i]] = index index += 1 elif t_dict[t[i]] != s_dict[s[i]]: return False return Truehttps://leetcode-cn.com/problems/isomorphic-strings/solution/python3-zi-dian-by-ting-ting-28-3/ 上述网址中具有另一种思路即判别映射关系是否一直符合 且 一直保持一一映射 如s = ‘abaq’ t=‘babp’ 则映射关系为 dict[a] = b(第一次出现) dict[b] = a(第一次出现) dict[a] = b(重复出现,符合) dict[q] = p(第一次出现) 代码如下
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: ref_dict = {} length = len(s) for i in range(length): if s[i] not in ref_dict: if t[i] not in ref_dict.values():#一一映射 ref_dict[s[i]] = t[i] else: return False else: if ref_dict[s[i]] != t[i]: return False else: pass return True