-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0290-word-pattern.py
More file actions
30 lines (28 loc) · 878 Bytes
/
0290-word-pattern.py
File metadata and controls
30 lines (28 loc) · 878 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
30
# time complexity: O(n+m)
# space complexity: O(n)
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
patternMap, wordMap = {}, {}
words = s.split(" ")
if len(words) != len(pattern):
return False
for char, word in zip(pattern, words):
if char not in patternMap:
if word in wordMap:
return False
else:
patternMap[char] = word
wordMap[word] = char
else:
if patternMap[char] != word:
return False
return True
pattern = "abba"
s = "dog cat cat dog"
print(Solution().wordPattern(pattern, s))
pattern = "abba"
s = "dog cat cat fish"
print(Solution().wordPattern(pattern, s))
pattern = "aaaa"
s = "dog cat cat dog"
print(Solution().wordPattern(pattern, s))