File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ # prefix ๊ธฐ๋ฐ์ผ๋ก ํ์ํ ์ ์๋ ํธ๋ผ์ด๋
ธ๋ ์๋ฃ๊ตฌ์กฐ ํ์ฉ
2+ class TrieNode :
3+ def __init__ (self ):
4+ self .children = {}
5+ self .is_ending = False
6+
7+ class WordDictionary :
8+
9+ def __init__ (self ):
10+ self .root = TrieNode ()
11+
12+ def addWord (self , word : str ) -> None :
13+ current_node = self .root
14+ for char in word :
15+ if char not in current_node .children :
16+ current_node .children [char ] = TrieNode ()
17+ current_node = current_node .children [char ]
18+ current_node .is_ending = True
19+
20+ def search (self , word ):
21+ def dfs (node , index ):
22+ # ๋จ์ด์๋ฆฌ์๋งํผ ์๊ณ , ๋๋จ์ด์ธ๊ฒฝ์ฐ ์ฐพ๊ธฐ ์ฑ๊ณต
23+ if index == len (word ):
24+ return node .is_ending
25+ # ์์ผ๋์นด๋์ธ ๊ฒฝ์ฐ ์์๋ค ์ ๋ถ ํ์
26+ if word [index ] == "." :
27+ for child in node .children .values ():
28+ if dfs (child , index + 1 ):
29+ return True
30+ # ์ผ๋ฐ์ ์ธ ๊ฒฝ์ฐ ๋ค์ ์์ ํ์
31+ if word [index ] in node .children :
32+ return dfs (node .children [word [index ]], index + 1 )
33+ return False
34+ return dfs (self .root , 0 )
35+
36+
37+ # Your WordDictionary object will be instantiated and called as such:
38+ # obj = WordDictionary()
39+ # obj.addWord(word)
40+ # param_2 = obj.search(word)
You canโt perform that action at this time.
0 commit comments