291. Word Pattern II
又是一道backtracking的题目,修修补补也算是AC了
class Solution(object):
def wordPatternMatch(self, pattern, s):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
m = {}
for c in pattern:
if c not in m:
m[c] = ""
return self.dfs(pattern, s, m, 0, 0)
def dfs(self, pattern, s, m, p, pos):
if pos == len(s) and p == len(pattern):
return True
if pos == len(s):
return False
if p == len(pattern):
return False
for i in range(pos, len(s)):
cur = s[pos:i+1]
cur_key = None
for key, value in m.iteritems():
if value == cur:
cur_key = key
if cur_key and cur_key != pattern[p]:
continue
if m[pattern[p]]:
if m[pattern[p]] == cur:
if self.dfs(pattern, s, m, p+1, i+1):
return True
else:
m[pattern[p]] = cur
if self.dfs(pattern, s, m, p+1, i+1):
return True
m[pattern[p]] = ""
return False