208. Implement Trie (Prefix Tree)
2021. 11. 17. 18:27ㆍLeetcode
Description:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String word) Inserts the string word into the trie.
- boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
- boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
class TrieNode:
def __init__(self,char):
self.char=char
self.children={}
self.isWord=False
class Trie:
def __init__(self):
self.root=TrieNode("")
def insert(self, word: str) -> None:
cur=self.root
for c in word:
if c in cur.children:
cur=cur.children[c]
else:
cur.children[c]=TrieNode(c)
cur=cur.children[c]
cur.isWord=True
def search(self, word: str) -> bool:
cur=self.root
for c in word:
if c in cur.children:
cur=cur.children[c]
else:
return False
return cur.isWord
def startsWith(self, prefix: str) -> bool:
cur=self.root
for c in prefix:
if c in cur.children:
cur=cur.children[c]
else:
return False
return True
# 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)
'Leetcode' 카테고리의 다른 글
106. Construct Binary Tree from Inorder and Postorder Traversal (0) | 2021.11.21 |
---|---|
540. Single Element in a Sorted Array (0) | 2021.11.20 |
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2021.11.17 |
62. Unique Paths (0) | 2021.11.17 |
230. Kth Smallest Element in a BST (0) | 2021.11.16 |