您的位置:首页 > 其它

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

2016-10-31 15:15 375 查看
题目:

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的。

运行速度还可以:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐