Given two stringssandt, 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.

Notice

You may assume both s and t have thesame length.

Have you met this question in a real interview?

Yes

Example

Given s ="egg", t ="add", returntrue.

Given s ="foo", t ="bar", returnfalse.

Given s ="paper", t ="title", returntrue.

class Solution:
    """
    @param s: a string
    @param t: a string
    @return: true if the characters in s can be replaced to get t or false
    """
    def isIsomorphic(self, s, t):

        #thinking process
        #one element can't be mapped into two different chars
        #no two characters may map to the same character

        #so we need two hash map to record the mapping
        #first represents the char from s to char from t
        #second represents the char from t to char from s

        #if a char from s already have a mapping, then we check if the result is the same
        #if a char hasn't been mapped, we check if the map_to value already been mapped from other char



        # write your code here
        if not s or not t:
            return False

        if len(s) != len(t):
            return False

        s_to_t = [0 for i in range(256)]
        t_to_s = [0 for i in range(256)]

        for char_s, char_t in zip(s, t):
            if s_to_t[ord(char_s)] != 0:
                if s_to_t[ord(char_s)] != ord(char_t):
                    return False
            else:
                if t_to_s[ord(char_t)] != 0 and t_to_s[ord(char_t)] != ord(char_s):
                    return False
                else:
                    s_to_t[ord(char_s)] = ord(char_t)
                    t_to_s[ord(char_t)] = ord(char_s)
        return True

results matching ""

    No results matching ""