Skip to content

Commit

Permalink
Leetcode Changes
Browse files Browse the repository at this point in the history
  • Loading branch information
SKAUL05 committed Apr 26, 2024
1 parent 9cabaf8 commit bb1670b
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions Leetcode/implement_trie_prefix_tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""
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.
Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
"""


class Trie(object):

def __init__(self):
self.trie = {}

def insert(self, word):
"""
:type word: str
:rtype: None
"""
trie = self.trie
for char in word:
if char not in trie:
trie[char] = {}
trie = trie[char]
trie["-"] = True

def search(self, word):
"""
:param word:
:return:
"""
trie = self.trie
for char in word:
if char not in trie:
return False
trie = trie[char]
return "-" in trie

def startsWith(self, word):
"""
:param word:
:return:
"""
trie = self.trie
for char in word:
if char not in trie:
return False
trie = trie[char]
return True


t = Trie()
t.insert("apple")
print(t.trie)
print(t.search("apple"))
print(t.search("app"))

0 comments on commit bb1670b

Please sign in to comment.