likes
comments
collection
share

LeetCode 205. 同构字符串

作者站长头像
站长
· 阅读数 71

题目地址(205. 同构字符串)

leetcode-cn.com/problems/is…

题目描述

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

如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。

每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

 

示例 1:

输入:s = "egg", t = "add"
输出:true


示例 2:

输入:s = "foo", t = "bar"
输出:false

示例 3:

输入:s = "paper", t = "title"
输出:true

 

提示:

可以假设 s 和 t 长度相同。

思路

用字典来遍历是否对应

代码

  • 语言支持:Python3

Python3 Code:


class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        resDict = dict()
        for index,val in enumerate(s):
            if val in resDict:
                if resDict[val] != t[index]:
                    return False
            else:
                resDict[val] = t[index]
        resDict = dict()
        for index,val in enumerate(t):
            if val in resDict:
                if resDict[val] != s[index]:
                    return False
            else:
                resDict[val] = s[index]
        return True

复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(n)O(n)O(n)
  • 空间复杂度:O(n)O(n)O(n)
转载自:https://juejin.cn/post/7023301649804296223
评论
请登录