291. Word Pattern II
题干:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.
解释:
给定一个字符串,要求进行判断是否能够和之前的模版进行匹配
思考:
就是无脑dfs。。。字符串的题真的很少看到无脑dfs的了。
答案:
def wordPatternMatch(self, pattern: str, str: str) -> bool:
m,n = len(pattern),len(str)
pattern_str = dict()
visited_str = set()
def helper(i,j):
if i == m and j == n: return True
if i == m or j == n or n - j < m - i: return False
for index in range(j, n):
sub_str = str[j:index + 1]
if pattern[i] in pattern_str and pattern_str[pattern[i]] == sub_str:
if helper(i + 1,index + 1): return True
## 我们要判断这两个字符或子串是否同时出现或者不出现,就要关注他们要一一对应的那个东西,也就是visited数组
## pattern中是否出现已经由pattern_str的键值存储,因此只需要保存str中是否出现
if not pattern[i] in pattern_str and not sub_str in visited_str:
pattern_str[pattern[i]] = sub_str
visited_str.add(sub_str)
if helper(i + 1,index + 1): return True
del pattern_str[pattern[i]]
visited_str.remove(sub_str)
return False
return helper(0,0)