forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sol.py
108 lines (95 loc) · 2.91 KB
/
sol.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""Leetcode version"""
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.prefixes = set()
self.words = set()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
for i in range(1, len(word)+1):
self.prefixes.add(word[:i])
self.words.add(word)
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
return word in self.words
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
return prefix in self.prefixes
# 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)
"""Proper TRIE (I like this one more)"""
class TrieNode:
def __init__(self, ch='*'):
self.links = []
self.char = ch
self.isWord = False
self.countPrefix = 0
def insert(self, root, word):
for letter in word:
foundPrefix = False
for link in root.links:
if link.char == letter:
foundPrefix = True
root.countPrefix += 1
root = link
break
else:
pass
if not foundPrefix:
newnode = TrieNode(letter)
root.links.append(newnode)
root = newnode
root.isWord = True
def search(self, root, word):
for i, letter in enumerate(word):
foundPrefix = False
for link in root.links:
if link.char == letter:
print(letter)
foundPrefix = True
return self.search(link, word[i+1::])
if not foundPrefix:
return False
if root.isWord:
return True
else:
print('Found but not a word')
return False
def startsWith(self, root, prefix):
for i, letter in enumerate(prefix):
foundPrefix = False
for link in root.links:
if link.char == letter:
print(letter)
foundPrefix = True
return self.startsWith(link, prefix[i+1:])
if not foundPrefix:
return False
return True
if __name__=='__main__':
root = TrieNode()
root.insert(root, 'hackathon')
print(root.search(root, 'hackathon'))
root.insert(root, 'apple')
print(root.search(root, 'apple'))
print(root.search(root, 'app'))
print(root.startsWith(root, 'app'))
root.insert(root, 'app')
print(root.search(root, 'app'))