일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Decorator
- data science
- 컴퓨터의 구조
- 315. Count of Smaller Numbers After Self
- 715. Range Module
- 30. Substring with Concatenation of All Words
- Protocol
- Substring with Concatenation of All Words
- t1
- 파이썬
- Python Implementation
- iterator
- 시바견
- 프로그래머스
- Convert Sorted List to Binary Search Tree
- 109. Convert Sorted List to Binary Search Tree
- LeetCode
- shiba
- Class
- Python Code
- DWG
- 43. Multiply Strings
- attribute
- Regular Expression
- concurrency
- Python
- 밴픽
- 운영체제
- kaggle
- Generator
Archives
- Today
- Total
Scribbling
LeetCode: 208. Implement Trie (Prefix Tree) 본문
Computer Science/Coding Test
LeetCode: 208. Implement Trie (Prefix Tree)
focalpoint 2021. 12. 9. 17:10class TrieNode:
def __init__(self):
self.children = {}
self.endFlag = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.endFlag = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.endFlag
def startsWith(self, prefix: str) -> bool:
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def delete(self, word):
def recursive(node, word, i):
if i == len(word):
if not node.endFlag:
return False
node.endFlag = False
return (len(node.children) == 0)
if word[i] not in node.children:
return False
need_delete = recursive(node.children[word[i]], word, i+1)
if need_delete:
node.children.pop(word[i])
return (len(node.children) == 0)
return False
recursive(self.root, word, 0)
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 337. House Robber III (0) | 2021.12.12 |
---|---|
LeetCode: 215. Kth Largest Element in an Array (0) | 2021.12.11 |
LeetCode: 136. Single Number (0) | 2021.12.09 |
LeetCode: 212. Word Search II (0) | 2021.12.08 |
LeetCode: 210. Course Schedule II (0) | 2021.12.07 |