forked from super30admin/Hashing-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem-14.py
29 lines (28 loc) · 1.06 KB
/
Problem-14.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
"""
Time complexity: O(n)
Space complexity: O(n)
Approach: Maintain a hashmap, mapping each unique letter in pattern to each unique word in s.
Maintain a set to mark all the unique words in s that have been already mapped.
When a new letter in pattern is mapped to a word different from one in the hashmap or
if a new letter is mapped to a word in t that is already mapped to a different letter
then we return false
else we return true.
"""
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
s = s.split()
if len(s) != len(pattern):
return False
mapping = {}
completed_set = set()
for i in range(len(s)):
if pattern[i] in mapping:
if mapping[pattern[i]] != s[i]:
return False
else:
if s[i] in completed_set:
return False
else:
mapping[pattern[i]] = s[i]
completed_set.add(s[i])
return True