-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0290_word_pattern.py
More file actions
29 lines (25 loc) · 887 Bytes
/
0290_word_pattern.py
File metadata and controls
29 lines (25 loc) · 887 Bytes
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(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
# list of words in str
split = str.split(' ')
# dict e.g. {dog: a, cat: b}
what = {}
# if the number of element in array is different from pattern
if (len(pattern) != len(split)):
return False
for i in range (len(pattern)):
# if str not saved in what
if (split[i] not in what):
# if it is really a new pattern
if (what == {}) or (pattern[i] not in pattern[:i]):
what[split[i]] = pattern[i]
else:
return False
elif (what[split[i]] != pattern[i]):
return False
return True