-
Notifications
You must be signed in to change notification settings - Fork 2
/
sol.py
43 lines (35 loc) · 1.08 KB
/
sol.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
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
patterns = self.getPatternsMap(pattern)
words = s.split(" ")
size = len(words)
if len(pattern) != size:
return False
used_words = {}
for key in patterns:
locations = patterns[key]
prev = None
for location in locations:
cur_word = words[location]
if location >= size:
return False
if prev is None:
prev = cur_word
if prev != cur_word:
return False
if cur_word in used_words:
return False
used_words[cur_word] = True
return True
def getPatternsMap(self, pattern: str) -> bool:
mapped = {}
for idx, c in enumerate(pattern):
if c not in mapped:
mapped[c] = []
mapped[c].append(idx)
return mapped
pattern = "aaa"
str = "aa aa aa aa"
sol = Solution()
res = sol.wordPattern(pattern, str)
print(res)