Leetcode: Isomorphic Strings


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   


你可能感兴趣的:(Leetcode: Isomorphic Strings)