返回

LeetCode205同构字符串是怎样的?用代码说给你听!

闲谈

前言

对于我们这些初入茅庐的编程小菜鸟来说,算法刷题是每天的必修课。在LeetCode的题库中,有一道题叫“同构字符串”,可以用代码说给你听,话不多说,咱们直接上代码!

核心代码

def isIsomorphic(s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    # 检查字符串长度是否相等
    if len(s) != len(t):
        return False

    # 使用两个字典来存储每个字符在两个字符串中的位置
    s_dict = {}
    t_dict = {}

    # 遍历字符串,检查字符是否对应
    for i in range(len(s)):
        if s[i] not in s_dict:
            s_dict[s[i]] = i
        if t[i] not in t_dict:
            t_dict[t[i]] = i

        # 检查字符是否对应
        if s_dict[s[i]] != t_dict[t[i]]:
            return False

    # 如果所有字符都对应,则返回True
    return True

运行效果

# 测试用例1
s = "egg"
t = "add"
print(isIsomorphic(s, t))  # True

# 测试用例2
s = "foo"
t = "bar"
print(isIsomorphic(s, t))  # False

# 测试用例3
s = "paper"
t = "title"
print(isIsomorphic(s, t))  # True

算法分析

  • 时间复杂度:O(n),其中n是字符串的长度。
  • 空间复杂度:O(n),其中n是字符串的长度。

总结

LeetCode 205. 同构字符串是判断两个字符串是否同构的经典算法题,非常适合初学者练习。希望本文能够帮助你更好地理解这道题。

扩展阅读