您的位置:首页 > 其它

Leetcode: Isomorphic Strings

2015-05-15 10:31 232 查看
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

[code]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.

[code]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:

[code]
Input:  "ab", "aa"
Output: true
Expected:   false


Correct Code

[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: