Skip to content

Commit 4273f10

Browse files
committed
implement trie prefix tree solution
1 parent b4d98cc commit 4273f10

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class TrieNode:
2+
def __init__(self):
3+
self.isEnd = False
4+
self.links = {}
5+
6+
7+
class Trie:
8+
9+
def __init__(self):
10+
self._root = TrieNode()
11+
12+
def _recurAdd(self, node: TrieNode, word: str) -> None:
13+
if not word:
14+
node.isEnd = True
15+
return
16+
17+
ch = word[0]
18+
# 부모 노드의 자식에 있는지 확인
19+
next_link = node.links.get(ch)
20+
21+
if not next_link:
22+
node.links[ch] = TrieNode()
23+
next_link = node.links[ch]
24+
25+
self._recurAdd(next_link, word[1:])
26+
27+
def insert(self, word: str) -> None:
28+
if not word:
29+
return
30+
31+
self._recurAdd(self._root, word)
32+
33+
def _recurSearch(self, node: TrieNode, word: str) -> bool:
34+
if not word:
35+
return node.isEnd
36+
37+
ch = word[0]
38+
next_link = node.links.get(ch)
39+
if next_link:
40+
return self._recurSearch(next_link, word[1:])
41+
return False
42+
43+
def search(self, word: str) -> bool:
44+
if not word:
45+
return False
46+
47+
return self._recurSearch(self._root, word)
48+
49+
def startsWith(self, prefix: str) -> bool:
50+
node = self._root
51+
for ch in prefix:
52+
if ch not in node.links:
53+
return False
54+
node = node.links[ch]
55+
return True
56+
57+
# Your Trie object will be instantiated and called as such:
58+
# obj = Trie()
59+
# obj.insert(word)
60+
# param_2 = obj.search(word)
61+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
 (0)