标签:turn ret inf object 因此 etc 需要 建立 zip
题目如下:
解题思路:本题的关键是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
标签:turn ret inf object 因此 etc 需要 建立 zip
原文地址:https://www.cnblogs.com/seyjs/p/9275607.html