Isomorphic Strings

来源:互联网 发布:车削编程 编辑:程序博客网 时间:2024/06/05 09:55

题目:

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.

解题思路:

由题意可看出,对于一个Isomorphic字符串,若将其每个字符与其对应的index构成一个hash表。其index项必然相同,此时若把一个hash表中的一个Isomorphic字符串的keys,换做另一个字符串的keys,他们必然相同。

"egg""add"。则有dic1={'e':[0],'g':[1,2]},dic2={'a':[0],'d':[1,2]}  ->dic1.values()==dic2.values()

"foo""bar"。则有dic1={'f':[0],'o':[1,2]},dic2={'a':[1],'b':[0],'r':[2]}    ->dic1.values()!=dic2.values()

"ab""ca".则有dic1={'a':[0],'b':[1]},dic2=['a':[1],'c':[0]]     ->sorted(dic1)==sorted(dic2)

代码:

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isIsomorphic(self, s, t):
        l1,l2 = list(s),list(t)
        dic1,dic2 = {},{}
        for index,letter in enumerate(l1):
            dic1[letter] = dic1.get(letter,[]) + [index]
        for index,letter in enumerate(l2):
            dic2[letter] = dic2.get(letter,[]) + [index]
        return sorted(dic1.values())==sorted(dic2.values())
            
        

0 0
原创粉丝点击