leetcode word pattern 以及 Isomorphic Strings --- 注意简便写法

题目很简单,https://leetcode.com/problems/word-pattern/


但是要写得最简单就不一样了。还可以用map



我的code写得有点复杂

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        

        dict1 = {}
        pl = list(pattern)
        sl = str.split()
        if len(pl) != len(sl):
            return False
        
        for i in xrange(len(pl)):
            if pl[i] in dict1:
                dict1[pl[i]].append(i)
            else:
                dict1[pl[i]] = [i]
        
        dict2 = {}
        
        for j in xrange(len(sl)):
            if sl[j] in dict2:
                dict2[sl[j]].append(j)
            else:
                dict2[sl[j]] = [j]

        list1 = [ tuple(x) for x in dict1.values()]
        list2 = [ tuple(x) for x in dict2.values()]

        set1 = set(list1)
        set2 = set(list2)

        if set1 == set2:
            return True
        else:
            return False

但是 可以用比较简单的语言。例如用到zip


class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        words = str.split()
        if len(pattern) != len(words):
            return False
        ptnDict, wordDict = {}, {}
        for ptn, word in zip(pattern, words):
            if ptn not in ptnDict:
                ptnDict[ptn] = word
            if word not in wordDict:
                wordDict[word] = ptn
            if wordDict[word] != ptn or ptnDict[ptn] != word:
                return False
        return True

另外两段更简单的

http://bookshadow.com/weblog/2015/10/05/leetcode-word-pattern/


注意map, filter, reduce用法

http://fcamel-fc.blogspot.hk/2011/08/python-1.html

def wordPattern(self, pattern, str):
    s = pattern
    t = str.split()
    return map(s.find, s) == map(t.index, t)



https://leetcode.com/problems/isomorphic-strings/



class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        a = list(s)
        b = list(t)
        
        if len(a) != len(b):
            return False
        
        dict1 = {}
        dict2 = {}
        for i,j in zip(a,b):
            if i not in dict1:
                dict1[i] = j
            if j not in dict2:
                dict2[j] = i
            if dict1[i] != j or dict2[j] != i:
                return False
        return True


你可能感兴趣的:(leetcode word pattern 以及 Isomorphic Strings --- 注意简便写法)