forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest-word-with-all-prefixes.py
63 lines (54 loc) · 1.88 KB
/
longest-word-with-all-prefixes.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
# Time: O(n)
# Space: O(t), t is the number of nodes in trie
import collections
import string
class Solution(object):
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
def iter_dfs(words, node):
result = -1
stk = [node]
while stk:
node = stk.pop()
if result == -1 or len(words[node["_end"]]) > len(words[result]):
result = node["_end"]
for c in reversed(string.ascii_lowercase):
if c not in node or "_end" not in node[c]:
continue
stk.append(node[c])
return result
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
trie["_end"] = -1
for i, word in enumerate(words):
reduce(dict.__getitem__, word, trie)["_end"] = i
result = iter_dfs(words, trie)
return words[result] if result != -1 else ""
# Time: O(n)
# Space: O(t), t is the number of nodes in trie
import collections
import string
class Solution2(object):
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
def dfs(words, node, result):
if result[0] == -1 or len(words[node["_end"]]) > len(words[result[0]]):
result[0] = node["_end"]
for c in string.ascii_lowercase:
if c not in node or "_end" not in node[c]:
continue
dfs(words, node[c], result)
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
trie["_end"] = -1
for i, word in enumerate(words):
reduce(dict.__getitem__, word, trie)["_end"] = i
result = [-1]
dfs(words, trie, result)
return words[result[0]] if result[0] != -1 else ""