【leetcode】290. Word Pattern
阿新 • • 發佈:2018-07-07
dpa mage split tco 兩個 true lse div att
題目如下:
解題思路:本題的關鍵是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 andw 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
【leetcode】290. Word Pattern