File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ # 문제유형 : Trie
2+ class WordDictionary :
3+ def __init__ (self ):
4+ self .trie = {}
5+
6+ # 시간 복잡도 : O(N)
7+ # 공간 복잡도 : O(N)
8+ def addWord (self , word : str ) -> None :
9+ node = self .trie
10+ for char in word :
11+ if char not in node :
12+ node [char ] = {}
13+ node = node [char ]
14+ node ['$' ] = True
15+
16+ # 시간 복잡도 : O(m^N) (m : 철자의 종류, N : 문자열의 길이)
17+ def search (self , word : str ) -> bool :
18+ return self .dfs (0 , self .trie , word )
19+
20+ def dfs (self , i , node , word ):
21+ if i == len (word ):
22+ return '$' in node
23+ if word [i ] == '.' :
24+ for child in node .values ():
25+ if isinstance (child , dict ) and self .dfs (i + 1 , child , word ):
26+ return True
27+ if word [i ] in node :
28+ return self .dfs (i + 1 , node [word [i ]], word )
29+ return False
30+
You can’t perform that action at this time.
0 commit comments