720. Longest Word in Dictionary
Given an array of strings words
representing an English Dictionary, return the longest word in words
that can be built one character at a time by other words in words
.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i]
consists of lowercase English letters.class TrieNode:
def __init__(self):
self.children = dict()
self.is_word = False
self.word = ""
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word):
curr = self.root
for c in word:
if c not in curr.children:
curr.children[c] = TrieNode()
curr = curr.children[c]
curr.is_word = True
curr.word = word
def bfs(self):
q = collections.deque([self.root])
answer = []
while q:
curr = q.popleft()
for i in curr.children.values():
if i.is_word:
q.append(i)
answer.append(i.word)
return answer
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
for word in words:
trie.add(word)
answer = trie.bfs()
return sorted(answer, key = lambda x : (-len(x), x))[0] if answer else ""