Python different solutions (dictionary, etc).


  • 50
    C
    def isIsomorphic1(self, s, t):
        d1, d2 = {}, {}
        for i, val in enumerate(s):
            d1[val] = d1.get(val, []) + [i]
        for i, val in enumerate(t):
            d2[val] = d2.get(val, []) + [i]
        return sorted(d1.values()) == sorted(d2.values())
            
    def isIsomorphic2(self, s, t):
        d1, d2 = [[] for _ in xrange(256)], [[] for _ in xrange(256)]
        for i, val in enumerate(s):
            d1[ord(val)].append(i)
        for i, val in enumerate(t):
            d2[ord(val)].append(i)
        return sorted(d1) == sorted(d2)
        
    def isIsomorphic3(self, s, t):
        return len(set(zip(s, t))) == len(set(s)) == len(set(t))
        
    def isIsomorphic4(self, s, t): 
        return [s.find(i) for i in s] == [t.find(j) for j in t]
        
    def isIsomorphic5(self, s, t):
        return map(s.find, s) == map(t.find, t)
    
    def isIsomorphic(self, s, t):
        d1, d2 = [0 for _ in xrange(256)], [0 for _ in xrange(256)]
        for i in xrange(len(s)):
            if d1[ord(s[i])] != d2[ord(t[i])]:
                return False
            d1[ord(s[i])] = i+1
            d2[ord(t[i])] = i+1
        return True

  • 1

    Did you really come up with all of these yourself?


  • 4
    C

    No, I come up the first two and the last one, while I think the middle ones are a little bit cheating in an interview.


  • 3

    "No"

    See plagiarism then.


  • 0
    C
    This post is deleted!

  • 0
    Y

    what a amazing jod! I love the 4th and 5th


  • 0
    G

    Thanks, man. Very helpful.


  • 2
    I
       class Solution(object):
            def isIsomorphic(self, s, t):
                """
                :type s: str
                :type t: str
                :rtype: bool
                """
                ns = len(s)
                nt = len(t)
                
                if ns != nt:
                    return False
                    
                h = {}
                mt = {}
                for i in range(ns):
                    if s[i] not in h:
                        if t[i] not in mt:
                            h[s[i]] = t[i]
                            mt[t[i]] = s[i]
                        else:
                            return False
                    elif h[s[i]] != t[i]:
                        return False
                    
                return True
    

  • 1
    Q
    def isIsomorphic(self, s, t):
        d1, d2 = dict(), dict()
        for v, w in zip(s,t):
            if (v in d1 and d1[v] != w) or (w in d2 and d2[w] != v):
                    return False
            d1[v], d2[w] = w, v
        return True

Log in to reply
 

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