判断是否为同构字符串

要想解答这个算法,得明白一个概念,什么是同构字符串,来看一下定义:

也就是说,s可以转化为t,对应的t也可以转化为s。

 

解决思路:

我们进行一次的遍历,然后定义了两个dict,来记录s->t,t->s的映射,然后在后面校验一下,这两个dict的value 是否是相同的,来上代码。

class Solution:
    def isIsomorphic(self, s: str, t: str):

        dict_s = {}
        dict_t = {}

        for s_i, t_i in zip(s, t):
            if s_i not in dict_s:
                dict_s[s_i] = ord(s_i) - ord(t_i)
            if t_i not in dict_t:
                dict_t[t_i] = ord(s_i) - ord(t_i)
        
        # 如果value不相同 就返回False  在py37后 dict是有序的
        for s_i, t_i in zip(s, t):
            if dict_s[s_i] != dict_t[t_i]:
                return False

        return True

 

 为什么定义了两个dict?用来避免不同的s对应相同的t,所以用两个dict来进行校验。

 

posted @ 2024-08-19 16:30  TW-NLP  阅读(2)  评论(0编辑  收藏  举报