-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm648 v2 TRIE.py
35 lines (29 loc) · 1.08 KB
/
m648 v2 TRIE.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
# V2 using Trie method that consistently hits 98% runtime but hovers around 60% memory
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
# Trie setup
trie = {}
for root in dictionary :
current = trie
for c in root :
if c in current :
current = current[c]
else :
current[c] = {}
current = current[c]
current['!'] = True # signifify end of dict word
# Output calculation making use of trie
output = sentence.split(' ')
for i in range(len(output)) :
current = trie
progress = []
for c in output[i] :
if current.get('!', False): # Found shortest prefix
output[i] = ''.join(progress)
break
if c in current :
progress.append(c)
current = current[c]
continue
break
return ' '.join(output)