Implement Trie
2026. 3. 15. 10:24ㆍAlgorithm/Leetcode, Lintcode, HackerRank, etc.
- 목차
반응형
class Node:
def __init__(self, value):
self.value = value
self.child = {}
self.eow = False
class Trie:
def __init__(self):
self.root = Node(None)
def insert(self, word: str) -> None:
if self.search(word):
return
cur = self.root
for ch in word:
if ch not in cur.child:
cur.child[ch] = Node(ch)
cur = cur.child[ch]
cur.eow = True
def search(self, word: str) -> bool:
cur = self.root
for ch in word:
if ch not in cur.child:
break
cur = cur.child[ch]
else:
return cur.eow
return False
def startsWith(self, prefix: str) -> bool:
cur = self.root
for ch in prefix:
if ch not in cur.child:
break
cur = cur.child[ch]
else:
return True
return False반응형
'Algorithm > Leetcode, Lintcode, HackerRank, etc.' 카테고리의 다른 글
| Count Commas in Range (0) | 2026.03.15 |
|---|---|
| Longest Univalve path (0) | 2026.03.15 |
| Binary Tree Level Order Traverse (0) | 2026.03.15 |
| Shortest Path in Binary Matrix (0) | 2026.03.12 |
| Network Delay Time (0) | 2026.03.12 |