Python solution using hash - suggestions/improvements will be appreciated.

  • 0
    """LOGIC: Assign elements in s as key, and elements in t as its corresponding values
    1. Iterate through the length of the list. (as it is given that the lengths are equal)
    2. If s[i] is not present in the dictionary, 
       a. To overcome s = "aa" t ="ab", check if t[i] is already present in dict.values(). If it is, then there is a duplicate, meaning, 2 keys have the same value, and that should not be the case. return False
       b. Else, add it as a key and assign t[i] as its value
    3. If it is present, check whether the value for that key is equal to t[i], if not return false
    4. Finally return True
    class Solution(object):
        def isIsomorphic(self, s, t):
            :type s: str
            :type t: str
            :rtype: bool
            dict = {}
            for i in range(len(s)):
                if s[i] not in dict:
                    if t[i] in dict.values():
                        return False
                    dict[s[i]] = t[i]
                    if dict[s[i]] != t[i]:
                        return False
            return True

  • -4
        if len(s)!=len(t):
            return False

    #you should add this judgement before the code

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.