-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.py
More file actions
94 lines (62 loc) · 1.95 KB
/
Trie.py
File metadata and controls
94 lines (62 loc) · 1.95 KB
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
# Prefix Tree / Trie code
class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word):
curr = self.root
for char in word:
if char not in curr.children:
curr.children[char] = TrieNode()
curr = curr.children[char]
curr.isWord = True
def get(self, word):
curr = self.root
for char in word:
if char not in curr.children:
return False
curr = curr.children[char]
print(curr.isWord)
return curr.isWord
trie = Trie()
trie.add('bob')
trie.add('bed')
trie.get('bob')
trie.get('bed')
trie.get('be')
## Itterating a full trie example
class Node:
def __init__(self):
self.children = {}
self.isWord = False
self.fullword = None
class Solution:
def longestWord(self, words: List[str]) -> str:
# add all to trie O(chars)
# run through trie to get smallest word O(chars)
trie = Node()
for word in words:
cur = trie
for char in word:
if char not in cur.children:
cur.children[char] = Node()
cur = cur.children[char]
cur.isWord = True
cur.fullword = word
res = ["", -1]
self.itterTrie(trie, res)
return res[0]
def itterTrie(self, trie, res):
for child in trie.children:
cur = trie.children[child]
if cur.isWord:
curLen = len(cur.fullword)
if curLen == res[1]:
res[0] = min(res[0], cur.fullword)
elif curLen > res[1]:
res[0] = cur.fullword
res[1] = curLen
self.itterTrie(cur, res)