Skip to content

Commit 8aa041a

Browse files
committed
Add 290
1 parent 54fa7ae commit 8aa041a

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
| 264 | Ugly Number II | Medium | O(1) | O(1) | Heap, Dynamic Programming | | |
3636
| 270 | Closest Binary Search Tree Value | Easy | O(H) | O(1) | Binary Search, Tree | | 🔒 |
3737
| 274 | H-Index | Medium | O(NlogN) | O(N) | Hash Table, Sort | There is a better solution | |
38+
| 290 | Word Pattern | Easy | O(N) | O(N) | Hash Table | | |
3839
| 295 | Find Median from Data Stream | Hard | O(logN) | O(N) | Design, Hard, Heap | | |
3940
| 319 | Bulb Switcher | Medium | O(1) | O(1) | Math, Tricky | | |
4041
| 328 | Odd Even Linked List | Medium | O(N) | O(1) | Linked List | | |

inputs/290

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
""abc"
2+
"b c a"
3+
"abc"
4+
"dog cat dog"
5+
"abba"
6+
"dog dog dog dog"
7+
"abba"
8+
"dog cat cat dog"
9+
""
10+
"beef""

src/290.word-pattern.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#
2+
# @lc app=leetcode id=290 lang=python3
3+
#
4+
# [290] Word Pattern
5+
#
6+
7+
# @lc code=start
8+
# TAGS: Hash Table
9+
10+
import itertools
11+
class Solution:
12+
# 36 ms, 66 % pythonic code using set
13+
def wordPattern1(self, pattern: str, str: str) -> bool:
14+
t = str.split()
15+
p = pattern
16+
return len(set(zip(p,t))) == len(set(p)) == len(set(t)) and len(p) == len(t)
17+
18+
# 32 ms, 60.84 %. Time and Space: O(N)
19+
def wordPattern(self, pattern: str, str: str) -> bool:
20+
S = str.split()
21+
if len(S) != len(pattern): return False
22+
match1 = {}
23+
match2 = {}
24+
for c, word in itertools.zip_longest(pattern, S):
25+
if c in match1 and word in match2:
26+
if match1[c] != word: return False
27+
if match2[word] != c: return False
28+
elif c not in match1 and word not in match2:
29+
match1[c] = word
30+
match2[word] = c
31+
else:
32+
return False
33+
return True
34+
35+
# 32 ms 89 %. Time and Space: O(N)
36+
def wordPattern(self, pattern: str, str: str) -> bool:
37+
S = str.split()
38+
if len(S) != len(pattern) or len(set(S)) != len(set(pattern)): return False
39+
D = {}
40+
for i, c in enumerate(pattern):
41+
if c in D and S[i] != D[c]: return False
42+
D[c] = S[i]
43+
return True
44+
45+
# @lc code=end

0 commit comments

Comments
 (0)