LeetCode 题解工作台
同构字符串
给定两个字符串 s 和 t ,判断它们是否是同构的。 如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。 每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。 示例 1: 输入…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用两个哈希表或数组 和 记录 和 中字符的映射关系。 遍历 和 ,如果 和 中对应的字符映射关系不同,则返回 `false`,否则更新 和 中对应的字符映射关系。遍历结束,说明 和 是同构的,返回 `true`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给定两个字符串 s 和 t ,判断它们是否是同构的。
如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。
每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。
示例 1:
输入:s = "egg", t = "add"
输出:true
解释:
字符串 s 和 t 可以通过以下方式变得相同:
- 将
'e'映射为'a'。 - 将
'g'映射为'd'。
示例 2:
输入:s = "f11", t = "b23"
输出:false
解释:
字符串 s 和 t 无法变得相同,因为 '1' 需要同时映射到 '2' 和 '3'。
示例 3:
输入:s = "paper", t = "title"
输出:true
提示:
1 <= s.length <= 5 * 104t.length == s.lengths和t由任意有效的 ASCII 字符组成
解题思路
方法一:哈希表或数组
我们可以用两个哈希表或数组 和 记录 和 中字符的映射关系。
遍历 和 ,如果 和 中对应的字符映射关系不同,则返回 false,否则更新 和 中对应的字符映射关系。遍历结束,说明 和 是同构的,返回 true。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度;而 为字符集大小,本题中 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.