Leetcode: Isomorphic Strings

本文探讨了如何判断两个字符串是否为同构性字符串,即通过替换字符,一个字符串可以完全转化为另一个字符串。分析了同构性的定义、特性,并提供了解决方案。同时指出了一个常见的错误解决方案及其改进,最终给出了正确实现和测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Get idea from here


Question

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

Note:
You may assume both s and t have the same length.

Hide Tags Hash Table


Analysis

s1, s2 are two chars
if s1 has mapped char:
    check whether mapped char is correct 
else:   #s1 has no corresponding char
    check whether s2 is the mapped char of some one else
    if yes:  return False
    if no: dict1[s1]=s2, dict2[s2]=s1       

Solution

Mistake taken

This solution can’t ensure that different s1 map to different s2. In this example, “a” and “b” both map to “a”. The tricky here is to create a new dict, to make sure one char maps to only one char.

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isIsomorphic(self, s, t):
        dict1 = {}

        for i in range(len(s)):
            s1,s2= s[i],t[i]
            if s1 in dict1:
                if s2!=dict1[s1]:
                    return False
            else:
                dict1[s1] = s2

        return True

Result:


Input:  "ab", "aa"
Output: true
Expected:   false

Correct Code

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isIsomorphic(self, s, t):
        dict1, dict2 = {}, {}

        for i in range(len(s)):
            s1,s2= s[i],t[i]
            if s1 in dict1:
                if s2!=dict1[s1]:
                    return False
            else:
                if s2 in dict2:
                    return False
                dict1[s1] = s2
                dict2[s2] = s1

        return True   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值