720. Longest Word in Dictionary
Đề Bài
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 <= 10001 <= words[i].length <= 30words[i]consists of lowercase English letters.
Thuật Toán & Kỹ Thuật
⏱️ Thời gian
O(n²)
💾 Không gian
O(n)
Lời Giải
Python
0720-longest-word-in-dictionary.py
class TrieNode:
def __init__(self):
self.isEndWord = False
self.word = ''
self.children = defaultdict(TrieNode)
class Trie:
def __init__(self):
self.root = TrieNode()
self.root.isEndWord = True
def insert(self, word):
root = self.root
for char in word:
root = root.children[char]
root.isEndWord = True
root.word = word
def find(self):
res = ''
dq = deque([self.root])
while dq:
n = len(dq)
for _ in range(n):
root = dq.popleft()
if not root.isEndWord:
continue
if len(res) < len(root.word) or root.word < res:
res = root.word
for child in root.children.values():
dq.append(child)
return res
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
for word in words:
trie.insert(word)
return trie.find()