File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ ์ด ๋ฌธ์ ๋ ๋จ์ด๋ฅผ ์ถ๊ฐํ๊ณ , ๊ฒ์ํ ๋ .์ ์์ผ๋ ์นด๋๋ก ์ฌ์ฉํ ์ ์๋ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๊ตฌํํด์ผ ํจ
3+ Trie ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ์ฌ .์ด ๋์ค๋ฉด ๋ชจ๋ ์์ ๋
ธ๋๋ฅผ ํ์ํด์ผ ํจ(์ฌ๊ท์ ๊ฒ์)
4+
5+ ์๊ฐ ๋ณต์ก๋:
6+ addWord: O(L) (L = ๋จ์ด ๊ธธ์ด)
7+ search: ์ต์
์ ๊ฒฝ์ฐ O(26^M) (M = ๋จ์ด ๊ธธ์ด, .์ด ์ฐ์๋ ๊ฒฝ์ฐ)
8+ *๊ฒ์ํ ๋จ์ด๊ฐ ๋ชจ๋ .๋ก ๊ตฌ์ฑ๋ ๊ฒฝ์ฐ (์: ....)
9+ ๊ฐ .์์ 26๊ฐ์ ์์ ๋
ธ๋๋ฅผ ๋ชจ๋ ํ์ํด์ผ ํ๋ฏ๋ก
10+
11+ ๊ณต๊ฐ ๋ณต์ก๋: O(N) (N = ๋ชจ๋ ๋จ์ด์ ์ด ๋ฌธ์ ์)
12+
13+ '''
14+
15+ class TrieNode :
16+ def __init__ (self ):
17+ self .children = {} # ๋ฌธ์ -> ์์ ๋
ธ๋์ ์ ์ฅ
18+ self .is_end = False # ๋จ์ด ๋ ํ์
19+
20+ class WordDictionary :
21+ def __init__ (self ):
22+ self .root = TrieNode ()
23+
24+ # ๋จ์ด๋ฅผ ๋ฌธ์๋ณ๋ก ํธ๋ผ์ด์ ์ถ๊ฐ
25+ def addWord (self , word : str ) -> None :
26+ node = self .root
27+ for char in word :
28+ if char not in node .children :
29+ node .children [char ] = TrieNode ()
30+ node = node .children [char ]
31+
32+ # ๋จ์ด ๋ ํ์
33+ node .is_end = True
34+
35+ # ๊น์ด ์ฐ์ ํ์(dfs)ํจ์๋ก ์ฌ๊ท์ ํ์.
36+ def search (self , word : str ) -> bool :
37+ def dfs (node , index ):
38+ if index == len (word ):
39+ return node .is_end
40+ char = word [index ]
41+ # .์ด๋ฉด ๋ชจ๋ ์์ ๋
ธ๋ ํ์
42+ if char != '.' :
43+ return char in node .children and dfs (node .children [char ], index + 1 )
44+ else :
45+ for child in node .children .values ():
46+ if dfs (child , index + 1 ):
47+ return True
48+ return False
49+
50+ return dfs (self .root , 0 )
51+
52+
You canโt perform that action at this time.
0 commit comments