File tree Expand file tree Collapse file tree 3 files changed +56
-0
lines changed Expand file tree Collapse file tree 3 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 35
35
| 264 | Ugly Number II | Medium | O(1) | O(1) | Heap, Dynamic Programming | | |
36
36
| 270 | Closest Binary Search Tree Value | Easy | O(H) | O(1) | Binary Search, Tree | | 🔒 |
37
37
| 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 | | |
38
39
| 295 | Find Median from Data Stream | Hard | O(logN) | O(N) | Design, Hard, Heap | | |
39
40
| 319 | Bulb Switcher | Medium | O(1) | O(1) | Math, Tricky | | |
40
41
| 328 | Odd Even Linked List | Medium | O(N) | O(1) | Linked List | | |
Original file line number Diff line number Diff line change
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""
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments