File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , ending = False ):
3
+ self .ending = ending
4
+ self .children = {}
5
+
6
+
7
+ class WordDictionary :
8
+
9
+ def __init__ (self ):
10
+ self .head = Node (True )
11
+
12
+ # ์๊ฐ๋ณต์ก๋: O(W)
13
+ def addWord (self , word : str ) -> None :
14
+ node = self .head
15
+
16
+ for ch in word :
17
+ if ch not in node .children :
18
+ node .children .setdefault (ch , Node ())
19
+ node = node .children [ch ]
20
+
21
+ node .ending = True
22
+
23
+ # ์๊ฐ๋ณต์ก๋: O(W*N) W: word ๊ธธ์ด N: ์์ ๋
ธ๋์ ๊ฐ์
24
+ def search (self , word : str ) -> bool :
25
+ def dfs (idx , node ):
26
+ if idx == len (word ):
27
+ return node .ending
28
+
29
+ if word [idx ] == '.' :
30
+ for n in node .children .values ():
31
+ if dfs (idx + 1 , n ):
32
+ return True
33
+ elif word [idx ] in node .children :
34
+ return dfs (idx + 1 , node .children [word [idx ]])
35
+ else :
36
+ return False
37
+
38
+ return dfs (0 , self .head )
You canโt perform that action at this time.
0 commit comments