LeetCode 题解工作台

同构字符串

给定两个字符串 s 和 t ,判断它们是否是同构的。 如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。 每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。 示例 1: 输入…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以用两个哈希表或数组 和 记录 和 中字符的映射关系。 遍历 和 ,如果 和 中对应的字符映射关系不同,则返回 `false`,否则更新 和 中对应的字符映射关系。遍历结束,说明 和 是同构的,返回 `true`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

 

示例 1:

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

输出:true

解释:

字符串 st 可以通过以下方式变得相同:

  • 将 'e' 映射为 'a'
  • 将 'g' 映射为 'd'

示例 2:

输入:s = "f11", t = "b23"

输出:false

解释:

字符串 st 无法变得相同,因为 '1' 需要同时映射到 '2''3'

示例 3:

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

输出:true

 

提示:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s 和 t 由任意有效的 ASCII 字符组成
lightbulb

解题思路

方法一:哈希表或数组

我们可以用两个哈希表或数组 d1d_1d2d_2 记录 sstt 中字符的映射关系。

遍历 sstt,如果 d1d_1d2d_2 中对应的字符映射关系不同,则返回 false,否则更新 d1d_1d2d_2 中对应的字符映射关系。遍历结束,说明 sstt 是同构的,返回 true

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为字符串 ss 的长度;而 CC 为字符集大小,本题中 C=256C = 256

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        d1 = {}
        d2 = {}
        for a, b in zip(s, t):
            if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
                return False
            d1[a] = b
            d2[b] = a
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate correctly identifies the need for two hash maps to track character mappings.

  • question_mark

    Evaluate the candidate's ability to ensure bijective character mappings without conflicts.

  • question_mark

    See if the candidate can explain the importance of maintaining the character order during transformation.

warning

常见陷阱

外企场景
  • error

    Not checking for bijective mapping, which can cause mapping conflicts where multiple characters map to the same character.

  • error

    Forgetting to handle cases where characters from one string map to themselves, such as when 'a' maps to 'a'.

  • error

    Relying on string comparison without using hash maps, which can lead to inefficiencies and incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider strings of varying lengths, ensuring the solution works for edge cases such as empty strings or strings with one character.

  • arrow_right_alt

    Handle cases where the strings are of equal length but contain a mix of uppercase and lowercase characters.

  • arrow_right_alt

    Test the solution with strings containing non-alphabetical ASCII characters to ensure robustness.

help

常见问题

外企场景

同构字符串题解:哈希·表·结合·string | LeetCode #205 简单