1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution: def wordPatternMatch(self, pattern, str): return self.isMatch(pattern, str, {}, set())
def isMatch(self, pattern, s, dic, used): if not pattern and not s: return True elif not pattern or not s: return False
ch = pattern[0] if ch in dic: word = dic[ch] n = len(word) if word == s[:n]: return self.isMatch(pattern[1:], s[n:], dic, used) else: return False else: for i in range(len(s)): if s[:i+1] in used: continue dic[ch] = s[:i+1] used.add(s[:i+1]) if self.isMatch(pattern[1:], s[i+1:], dic, used): return True used.remove(s[:i+1]) del dic[ch] return False
|