leetcode word pattern 및 Isomorphic Strings – 간단한 쓰기 주의

2748 단어
제목은 간단하지만,https://leetcode.com/problems/word-pattern/
하지만 가장 간단하게 쓰면 달라진다.맵도 쓸 수 있어요.
제 코드는 좀 복잡하게 썼어요.
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/
맵,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

좋은 웹페이지 즐겨찾기