Question:
Implement a trie with insert, search, and startsWith methods.
Source:
https://leetcode.com/problems/implement-trie-prefix-tree/description/
The Trie object will be instantiated and called as such:
obj = Trie()
obj.insert(word)
param_2 = obj.search(word)
param_3 = obj.startsWith(prefix)
Code:
I have a TrieNode class and a Trie class. I'm not sure if I can make my code more pythonic. I ran the code on leetcode and it passed all the testcases.
class TrieNode:
def __init__(self):
self.children = [0]*26
self.end = False
def put(self, ch):
self.children[ord(ch)-ord('a')] = TrieNode()
def get(self, ch):
return self.children[ord(ch)-ord('a')]
def contains_key(self, ch):
return self.children[ord(ch)-ord('a')] != 0
def set_end(self):
self.end = True
def is_end(self):
return self.end
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
curr = self.root
for i in range(len(word)):
if not curr.contains_key(word[i]):
curr.put(word[i])
curr = curr.get(word[i])
curr.set_end()
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.root
for i in range(len(word)):
if not curr.contains_key(word[i]):
return False
curr = curr.get(word[i])
return True if curr.is_end() else False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
curr = self.root
for i in range(len(prefix)):
if not curr.contains_key(prefix[i]):
return False
curr = curr.get(prefix[i])
return True