Problem:
Implement a trie with insert
, search
, and startsWith
methods.
Example:
1 | Trie trie = new Trie(); |
Methods & Solutions:
- Frist method using
TrieNode
First define a
TrieNode
class, it has two attributes, one ischildren
, the other isisWord
. Attributechildren
represents the sub nodes of parent node. Since one node may have many different sub nodes, I setchildren
intodict()
orcollections.defaultdict()
. AttributeisWord
means weather this character is the end of inserted word, it will be used intrie.serach()
. we initializeisWord = False
, then if the character is the end of word, we set it intoTrue
.1
2
3
4
5
6class TrieNode:
def __init__(self):
self.children = {} # store characters of a word according ro their indices
# self.children = collections.defaultdict(TrieNode)
self.isWord = FalseDefine
__init__
in classTrie
1
2
3
4
5
6class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode() # root node is an empty node.Define
insert
in classTrie
1
2
3
4
5
6
7
8
9
10
11
12def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root # begin from root node in Trie
for w in word:
if w not in node.children:
node.children[w] = TrieNode() # store character in node.children
node = node.children[w] # update current node into its children node
node.isWord = True # this node represent the last character of wordDefine
search
in classTrie
1
2
3
4
5
6
7
8
9
10def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root # begin from root node, which is empty
for w in word:
# if character w not in inserted word, return False
if w not in node.children: return False
node = node.children[w] # update current node
return node.isWord # judge if it is the end characterDefine
startsWith
in classTrie
1
2
3
4
5
6
7
8
9
10def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root # begin from root node, which is empty
for w in prefix:
if w not in node.children: return False
node = node.children[w]
return True
- Second method using
dict()
from python
Instead of creating new TrieNode
class, we just use dict
here. Each dict
represents a node.
1 | class Trie: |