LeetCode- 同构字符串

给定两个字符串 s 和 t,判断它们是否是同构的。

如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

示例 1:

输入: s = “egg”, t = “add”
输出: true
示例 2:

输入: s = “foo”, t = “bar”
输出: false

class Solution:
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic = {}                                
        i = 0
        while i < len(s):
            if s[i] not in dic:
                if t[i] in dic.values():
                    return False
                dic[s[i]] = t[i]
            else:
                if dic[s[i]] != t[i]:
                    return False
            i += 1
        return True

题目已经提示两个字符串存在映射关系
用字典来接收两字符串的映射关系

if s[i] not in dic:
    if t[i] in dic.values():
        return False
    dic[s[i]] = t[i]

如果s[i]不在dic中,但是t[i]已在dic的values中,返回False
如果s[i]不在dic中,t[i]不在dic的values中,把新的映射关系加入字典

else:
    if dic[s[i]] != t[i]:
        return False

如果在s[i]在字典中,但是其在字典中已经存在的对应值不等于t[i],返回False
如果顺序执行完毕都没有return,说明映射关系成立,返回True

猜你喜欢

转载自blog.csdn.net/brook_/article/details/80207429