-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path1858-longest-word-with-all-prefixes.py
52 lines (40 loc) · 1.32 KB
/
1858-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
# time complexity: O(n*l)
# space complexity: O(n*l)
from typing import List
class Trie:
class TrieNode:
def __init__(self):
self.children = {}
self.isEndOfWord = False
def __init__(self):
self.root = self.TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = self.TrieNode()
node = node.children[char]
node.isEndOfWord = True
def hasAllPrefixes(self, word):
node = self.root
for char in word:
if (char not in node.children or not node.children[char].isEndOfWord):
return False
node = node.children[char]
return True
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
longestValidWord = ""
for word in words:
trie.insert(word)
for word in words:
if trie.hasAllPrefixes(word):
if len(word) > len(longestValidWord) or (
len(word) == len(longestValidWord)
and word < longestValidWord
):
longestValidWord = word
return longestValidWord
words = ["abc", "bc", "ab", "qwe"]
print(Solution().longestWord(words))