写一个方法判断给定的字符串是否同态(isomorphic)

66 阅读1分钟

"```markdown

判断字符串是否同态

同态字符串是指两个字符串中的字符可以一一映射,使得每个字符在转换过程中保持一致性。两个字符串被称为同态,当且仅当它们具有相同的结构。

方法思路

  1. 如果两个字符串的长度不同,则它们不可能是同态。
  2. 使用两个字典来记录字符的映射关系。
  3. 遍历两个字符串,检查每对字符的映射。
  4. 如果发现矛盾的映射关系,则返回False。
  5. 遍历结束后,返回True。

Python实现

def is_isomorphic(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False
    
    # 创建两个字典,用于存储字符映射
    s_to_t, t_to_s = {}, {}
    
    for char_s, char_t in zip(s, t):
        # 检查s到t的映射
        if char_s in s_to_t:
            if s_to_t[char_s] != char_t:
                return False
        else:
            s_to_t[char_s] = char_t
        
        # 检查t到s的映射
        if char_t in t_to_s:
            if t_to_s[char_t] != char_s:
                return False
        else:
            t_to_s[char_t] = char_s
    
    return True

示例

print(is_isomorphic(\"egg\", \"add\"))  # 输出: True
print(is_isomorphic(\"foo\", \"bar\"))  # 输出: False
print(is_isomorphic(\"paper\", \"title\"))  # 输出: True
print(is_isomorphic(\"ab\", \"aa\"))  # 输出: False

复杂度分析

  • 时间复杂度:O(n),其中n是字符串的长度。我们只需遍历字符串一次。
  • 空间复杂度:O(1),映射字符的数量最多为256(ASCII字符范围)。

总结

通过上述方法,可以有效地判断两个字符串是否同态。该算法简单明了,利用字典结构实现映射关系判断,能够处理大量字符的情况,且性能表现良好。