Python solution with detailed explanation


  • 0
    G

    Solution

    Isomorphic Strings https://leetcode.com/problems/isomorphic-strings/?tab=Description

    Algorithm

    • Every character in s must map to same character in t. Check using a dictionary.
    • No two characters in s should map to the same character in t. If 'a' maps to 'b', then no other character in s can map to b. This means no duplicates in values in iso_map.
    class Solution(object):
        def isIsomorphic(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            iso_map = {}
            for s1, t1 in zip(s,t):
                if s1 not in iso_map:
                    iso_map[s1] = t1
                elif iso_map[s1] != t1:
                    return False
            return len(set(iso_map.values())) == len(iso_map.values())
    

Log in to reply
 

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