File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Trie(object):
2+
3+ def __init__(self):
4+ """
5+ Initialize your data structure here.
6+ """
7+ self.children = [None]*26
8+ self.isEndofWord = False
9+
10+
11+
12+ def insert(self, word):
13+ """
14+ Inserts a word into the trie.
15+ :type word: str
16+ :rtype: None
17+ """
18+ curr=self
19+ for i in word:
20+ index = ord(i)-ord('a')
21+ if curr.children[index]==None:
22+ curr.children[index]=Trie()
23+ curr= curr.children[index]
24+ curr.isEndofWord = True
25+
26+
27+
28+
29+ def search(self, word):
30+ """
31+ Returns if the word is in the trie.
32+ :type word: str
33+ :rtype: bool
34+ """
35+ curr=self
36+ for i in word:
37+ index = ord(i)-ord('a')
38+ curr = curr.children[index]
39+ if curr== None:
40+ return False
41+ if curr.isEndofWord:
42+ return True
43+ return False
44+
45+
46+ def startsWith(self, prefix):
47+ """
48+ Returns if there is any word in the trie that starts with the given prefix.
49+ :type prefix: str
50+ :rtype: bool
51+ """
52+ curr=self
53+ for i in prefix:
54+ index = ord(i)-ord('a')
55+ curr = curr.children[index]
56+ if curr== None:
57+ return False
58+ return True
59+
60+
61+
62+
63+ # Your Trie object will be instantiated and called as such:
64+ # obj = Trie()
65+ # obj.insert(word)
66+ # param_2 = obj.search(word)
67+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments