Skip to content

Commit e5cb040

Browse files
committed
feat: implement Trie data structure with insert, search, and startsWith methods
1 parent 30cb3a7 commit e5cb040

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Node:
2+
"""
3+
Trie 자료구조의 노드를 나타내는 클래스.
4+
5+
key: 노드의 키 (문자)
6+
data: 노드에 저장된 데이터 (단어)
7+
children: 자식 노드들을 저장함 (키: 문자, 값: Node 객체)
8+
"""
9+
def __init__(self, key, data=None):
10+
self.key = key
11+
self.data = data
12+
self.children = {}
13+
14+
15+
class Trie:
16+
"""
17+
Trie 자료구조를 구현한 클래스.
18+
19+
head: Trie의 루트 노드
20+
21+
insert(word): 단어를 Trie에 삽입하는 메서드
22+
search(word): Trie에서 단어가 존재하는지 확인하는 메서드
23+
startsWith(prefix): Trie에서 접두사가 존재하는지 확인하는 메서드
24+
25+
- 시간 복잡도: O(M) (M은 단어의 길이)
26+
- 공간 복잡도: O(N * M) (N은 단어의 개수, M은 단어의 최대 길이)
27+
"""
28+
def __init__(self):
29+
self.head = Node(None)
30+
31+
def insert(self, word: str) -> None:
32+
curr = self.head
33+
for char in word:
34+
if char not in curr.children:
35+
curr.children[char] = Node(char)
36+
curr = curr.children[char]
37+
curr.data = word
38+
39+
def search(self, word: str) -> bool:
40+
curr = self.head
41+
for char in word:
42+
if char not in curr.children:
43+
return False
44+
curr = curr.children[char]
45+
return True if curr.data == word else False
46+
47+
def startsWith(self, prefix: str) -> bool:
48+
curr = self.head
49+
for char in prefix:
50+
if char not in curr.children:
51+
return False
52+
curr = curr.children[char]
53+
return True
54+
55+
56+
# Your Trie object will be instantiated and called as such:
57+
# obj = Trie()
58+
# obj.insert(word)
59+
# param_2 = obj.search(word)
60+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
 (0)