<LeetCode><Easy> 205 Isomorphic Strings --HashTable

来源:互联网 发布:淘宝怎么申请小号 编辑:程序博客网 时间:2024/05/19 19:31

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.


#Python2  68ms

#索引本身是非常有用的

class Solution(object):    def isIsomorphic(self, s, t):        return [s.index(i) for i in s]==[t.index(i) for i in t]

#加入预判   76ms

class Solution(object):    def isIsomorphic(self, s, t):        if len(set(s)) != len(set(t)):return False        return [s.index(i) for i in s]==[t.index(i) for i in t]       

Python2 60ms

#使用distinct方式串接

class Solution(object):    def isIsomorphic(self, s, t):        aList=list(set(map(lambda a,b:a+b,s,t)))        return (len(set([a[1] for a in aList]))==len(aList)==len(set([a[0] for a in aList])))

#加入预判  56ms

class Solution(object):    def isIsomorphic(self, s, t):        if len(set(s)) != len(set(t)):return False        aList=list(set(map(lambda a,b:a+b,s,t)))        return (len(set([a[1] for a in aList]))==len(aList)==len(set([a[0] for a in aList])))

#python2   各自distinct   280ms

class Solution(object):    def isIsomorphic(self, s, t):        sDistinct,tDistinct,length=[],[],len(s)        for i in xrange(length):            status= (t[i] in tDistinct) + (s[i] in sDistinct)            if status==2:                if sDistinct.index(s[i]) != tDistinct.index(t[i]):return False                else:continue            if status==1:                return False            sDistinct.append(s[i])            tDistinct.append(t[i])        return True



0 0