720. 词典中最长的单词 (tire 应用)
难度简单
给出一个字符串数组 words
组成的一本英语词典。返回 words
中最长的一个单词,该单词是由 words
词典中其他单词逐步添加一个字母组成。
若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
示例 1:
输入:words = ["w","wo","wor","worl", "world"] 输出:"world" 解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。
示例 2:
输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] 输出:"apple" 解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply"
from collections import defaultdict class Trie: def __init__(self): self.children = defaultdict(Trie) self.is_end = False def insert(self,word): node = self for ch in word: node = node.children[ch] node.is_end = True class Solution: def __init__(self): self.root = Trie() self.res = "" def longestWord(self, words: List[str]) -> str: for word in words: self.root.insert(word) def dfs(path,root): if root == None: return if root.is_end and len(path) > len(self.res): self.res = path for i in range(26): ch = chr(ord('a') + i) if root.children and root.children[ch].is_end: dfs(path+ch,root.children[ch]) dfs("",self.root) return self.res
1 struct TrieNode { 2 bool is_end; 3 std::vector<TrieNode*> children; 4 TrieNode() { 5 this->is_end = false; 6 this->children = std::vector<TrieNode*>(26); 7 } 8 }; 9 10 11 class Solution { 12 TrieNode* root = new TrieNode(); 13 string long_str = ""; 14 public: 15 void insert(string word) { 16 TrieNode* node = root; 17 for(auto ch : word) { 18 if (node->children[ch - 'a'] == nullptr) { 19 node->children[ch - 'a'] = new TrieNode(); 20 } 21 node = node->children[ch - 'a']; 22 } 23 node->is_end = true; 24 } 25 void dfs(TrieNode* node,string& path) { 26 if (path.size() > long_str.size()) { 27 long_str = path; 28 } 29 for(int i = 0; i < 26;i++) { 30 if (node->children[i] != nullptr && node->children[i]->is_end ) { 31 path+=('a' + i); 32 dfs(node->children[i],path); 33 path.pop_back(); 34 } 35 } 36 } 37 string longestWord(vector<string>& words) { 38 for(auto word : words) { 39 insert(word); 40 } 41 string path = ""; 42 dfs(root,path); 43 return long_str; 44 } 45 };