当前位置:网站首页>LeetCode: 205. Isomorphic Strings - Simple
LeetCode: 205. Isomorphic Strings - Simple
2022-08-06 15:02:00 【Kinght_123】

题目
205. 同构字符串
给定两个字符串 s 和 t ,判断它们是否是同构的.
如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的.
每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序.不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身.
示例 1:
输入:s = "egg", t = "add"
输出:true
示例 2:
输入:s = "foo", t = "bar"
输出:false
示例 3:
输入:s = "paper", t = "title"
输出:true
提示:
- 1 <= s.length <= 5 * 104
- t.length == s.length
- s 和 t 由任意有效的 ASCII 字符组成
解题思路1
- 直接利用indexfunction to compare the relative position of two arrays.
Code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
for i in range(len(s)):
if s.index(s[i]) != t.index(t[i]):
return False
return True
运行结果

解题思路2
- Use the idea of a hash table to solve the problem.
- We need to maintain two hash tables,The first hash table starts with sThe characters in are keys,映射到tThe characters in are numeric values;The second hash table starts with tThe characters in are keys,映射到sThe characters in are numeric values,Both hash tables are continuously updated,until a conflict arises,返回错误.
- Format of the specific conflict:If the character corresponding to the current subscript already exists,But not the same as the previous mapping.(The previous mapping can be either the mapping in the first hash table or the mapping in the second hash table).
- In layman's terms, we have already stored this character when we updated the hash table before,Then when we traverse to this character again, we find that it is different from the previously stored value,就产生了冲突,返回false.
Code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
hash1 = {
}
hash2 = {
}
for i in range(len(s)):
if (s[i] in hash1 and hash1[s[i]] != t[i]) or (t[i] in hash2 and hash2[t[i]] != s[i]):
return False
hash1[s[i]] = t[i]
hash2[t[i]] = s[i]
return True
运行结果

边栏推荐
- paper speed reading column index
- 如何从一个空有上进心的人,变成行动上的巨人?
- 【paper速读】NLNL: Negative Learning for Noisy Labels (ICCV2019)
- 传奇开服教程:传奇无限制仓库脚本分享
- 【LeetCode】658. Find the K closest numbers
- LeetCode_Recursive_Medium_397. Integer Substitution
- 梅科尔工作室OpenHarmony设备开发培训笔记-第7章学习笔记
- 如何判断一款GameFi游戏是否有发展空间?
- Tencent Cloud Hu Qiming: Analysis and Optimization of Kubernetes Cloud Resources
- SAP BAPI 教程 – 在 ABAP 中创建 BAPI 的分步指南-020
猜你喜欢
随机推荐
LeetCode_递归_中等_397.整数替换
作者简介&系列文章
Intel转型未成功而陷入亏损,AMD再次增长并获得可观的利润
西湖大学教授怎么看AI制药革命?|量子位智库圆桌实录
【组成原理 七 I/O系统】
LeetCode 0174. 地下城游戏
深入浅出边缘云 | 5. 运行时控制
两个Set集合获取相同的元素
LeetCode:205. 同构字符串————简单
ERC4907 的到来 会给 NFT 带来哪些变革?
终于有人把IaaS、PaaS、SaaS讲明白了
自然语言处理的前世、今生和未来
LeetCode 热题 HOT 100(2.两数相加)
LeetCode刷题日记:1545. 找出第 N 个二进制字符串中的第 K 位
Frida系列--Stalker原理分析
中科院打脸谷歌:普通电脑追上量子优越性,几小时搞定原本要一万年的计算...
软件测试基础理论
中国制造实力强横的又一证明,500强的中国企业数量最多
mv-lcd初始化
LeetCode Diary: 135. Distributing Candy








