Leetcode 290. Word Pattern & 291. Word Pattern II
word pattern
题目
解法:双hashmap
判断他们是否matching的关键在于,pattern中的某个字母和s中的单词是不是双向1-1对应的。要表达这种双向1-1对应的关系可以用两个字典,每个字典表示一种映射方向
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
map_from_letter_to_word = {
}
map_from_word_to_letter = {
}
st = str.split(' ')
if len(st) != len(pattern):
return False
for x,y in zip(pattern,st):
if x not in map_from_letter_to_word:
map_from_letter_to_word[x] = y
if y not in map_from_word_to_letter:
map_from_word_to_letter[y] = x
if map_from_word_to_letter[y] != x or map_from_letter_to_word[x] != y:
return False
return True
word pattern II
题目:
解法:双hashmap+backtracking
这道题跟上面一道题的唯一区别在于,现在的S是连续的。对于连续的S,比较常见的做法就是用backtracking进行暴力搜索。通过backtracking将他分割成所有可能的combination,并且判断双向的对应关系是否符合。具体流程如下:
- 给定一个pattern所在的位置i,s中所在的位置j
- 首先判断pattern[i]有没有已经存在的映射,如果有的话,那么现在s[j:j+k]对应的word要和现在pattern[i]对应的word相同,然后进行下一层matching,否则证明已经不符合matching
- 如果pattern[i]不存在已知映射,那么我们应该枚举pattern[i]映射到以j为index开始的任意的s中的sub string对应,这边就需要backtracking
看文字解释确实有点费解,看代码可能会更好理解
class Solution:
def wordPatternMatch(self, pattern: str