-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path291 Word Pattern II.py
49 lines (41 loc) · 1.24 KB
/
291 Word Pattern II.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
Premium Question
Author: Rajeev Ranjan
"""
class Solution(object):
def wordPatternMatch(self, pattern, s):
"""
Backtracking with prune
:type pattern: str
:type s: str
:rtype: bool
"""
return self.dfs(pattern, s, {}, set())
def dfs(self, pattern, s, char2word, words):
"""
Loop & DFS
:return: pattern can match s
"""
if not pattern and s or not s and pattern:
return False
if not pattern and not s:
return True
if pattern[0] in char2word:
word = char2word[pattern[0]]
if s[:len(word)] != word:
return False
else:
assert word in words
return self.dfs(pattern[1:], s[len(word):], char2word, words)
else:
for i in xrange(len(s)):
word = s[:i+1]
if word in words:
continue
char2word[pattern[0]] = word
words.add(word)
if self.dfs(pattern[1:], s[len(word):], char2word, words):
return True
words.remove(word)
del char2word[pattern[0]]
return False