【leetcode】290. Word Pattern

题目如下:

解题思路:本题的关键是pattern和word之间必须是一对一的关系。因此需要建立pattern->word和word->pattern两种映射,这两种映射可用两个字典分别保存。

代码如下:

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
        dic_p_to_w = {}
        dic_w_to_p = {}
        for p,w in zip(pattern,words):
            if p not in dic_p_to_w and w not in dic_w_to_p:
                dic_p_to_w[p] = w
                dic_w_to_p[w] = p
            elif p in dic_p_to_w and w in dic_w_to_p:
                if (dic_p_to_w[p] == w and dic_w_to_p[w] == p) == False:
                    return False
            else:
                return False
        return True

 

posted @ 2018-07-06 21:21  seyjs  阅读(171)  评论(0编辑  收藏  举报