Word Pattern II
要点:
- 注意与I的差异,其实题不难,看到这种迷乱的,首先要想到backtrack
- 1:1 mapping两个条件:p in and str in, or p not in and str not in values().
错误点:
- false的退出条件是pattern没有足够字符1:1了(i.e., len(pattern)>len(str)),但true的条件是pattern和str都比完了
# 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.
# Examples:
# pattern = "abab", str = "redblueredblue" should return true.
# pattern = "aaaa", str = "asdasdasdasd" should return true.
# pattern = "aabb", str = "xyzabcxzyabc" should return false.
# Notes:
# You may assume both pattern and str contains only lowercase letters.
# Hide Company Tags Dropbox Uber
# Hide Tags Backtracking
# Hide Similar Problems (E) Word Pattern
class Solution(object):
def wordPatternMatch(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pattern_map = {}
def helper(pattern, str):
if not pattern and not str:
return True
if not pattern or not str:
return False
if len(pattern)>len(str):
return False
p = pattern[0]
if p in pattern_map:
if str[:len(pattern_map[p])]!=pattern_map[p]:
return False
else:
return helper(pattern[1:], str[len(pattern_map[p]):])
for i in xrange(len(str)):
substr = str[:i+1]
if substr not in pattern_map.values():
pattern_map[p]=str[:i+1]
if helper(pattern[1:], str[i+1:]):
return True
del pattern_map[p]
return False
return helper(pattern, str)
sol = Solution()
assert sol.wordPatternMatch("abab", "redblueredblue")==True, "must be True"
assert sol.wordPatternMatch("aaaa", "asdasdasdasd")==True, "must be True"
assert sol.wordPatternMatch("aabb", "xyzabcxzyabc")==False, "must be False"