-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path290_Word_Pattern.py
More file actions
93 lines (66 loc) · 2.17 KB
/
290_Word_Pattern.py
File metadata and controls
93 lines (66 loc) · 2.17 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Two hash map
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
if len(pattern) != len(words):
return False
charToWord = {}
wordToChar = {}
for c, w in zip(pattern, words):
if c in charToWord and charToWord[c] != w:
return False
if w in wordToChar and wordToChar[w] != c:
return False
charToWord[c] = w
wordToChar[w] = c
return True
// 2nd way
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
charToWord = {}
wordToChar = {}
words = s.split()
if len(pattern) != len(words):
return False
for i, (c, word) in enumerate(zip(pattern, words)):
if charToWord.get(c, 0) != wordToChar.get(word, 0):
return False
charToWord[c] = i + 1
wordToChar[word] = i + 1
return True
// hash set
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
charToWord = {}
store = set()
for i, (c, w) in enumerate(zip(pattern, words)):
if c in charToWord:
if words[charToWord[c]] != w:
return False
else:
if w in store:
return False
charToWord[c] = i
store.add(w)
return True
// Single Hash Map
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
charToWord = {}
for i, (c, w) in enumerate(zip(pattern, words)):
if c in charToWord:
if words[charToWord[c]] != w:
return False
else:
# iterates atmost 26 times (a - z)
for k in charToWord:
if words[charToWord[k]] == w:
return False
charToWord[c] = i
return True