leetcode_205. Isomorphic Strings 字符串同构,由一个字符串映射到另一个字符串,一一映射

题目:

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.


题意:

判断两个字符串是否同构,同构代表字符串t中的字符可以由s中的字符映射过来,即s中的字符通过替换能够得到t。不允许出现多个字符替换到同一个字符的情况,即只能一一映射。

代码:

class Solution(object):

    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        lens = len(s)
        lent = len(t)
        
        if lens != lent :
            return False
        else :
            dict1 = dict()                      #判断从s到t的映射,保证在s中同一个字符在t中只有一个值与其对应,保证s中字符的一一映射
            for i in range(lens) :          #能解决s='aa', t='ab'的情况,但不能解决s='ab', t='aa'的情况
                if s[i] not in dict1 :
                    dict1[s[i]] = t[i]
                else :
                    if dict1[s[i]] != t[i] :         #如果s[i]已在字典中,但是在t中被映射到其他的字符,则不是一一映射
                        return False
            
            dict2 = dict()                       #判断从t到s的映射,保证在t中同一个字符在s中只有一个值与其对应,保证t中字符的一一映射
            for i in range(lent) :             #解决s='ab', t='aa'的情况
                if t[i] not in dict2 :
                    dict2[t[i]] = s[i]
                else :
                    if dict2[t[i]] != s[i] :
                        return False
            
            return True                               #当从s到t,和从t到s,都是一一映射后,则s与t同构

笔记:

刚开始只想到判断从s到t的一一映射,没考虑t到s的,运行失败后,看到测试用例才知道还要考虑从t到s的。

运行速度还可以:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值