LeetCode 720. 词典中最长的单词(Trie树)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 720. 词典中最长的单词(Trie树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給出一個字符串數組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"。注意: 所有輸入的字符串都只包含小寫字母。 words數組長度范圍為[1,1000]。 words[i]的長度范圍為[1,30]。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-word-in-dictionary
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. Trie樹解題
題目意思:從1個字母開始,每次增加一個字母(包含原始字母在內的每一步組成的單詞都必須在字典中找的到),最終形成的最長單詞是誰
- 對所有的單詞,插入Trie樹
- 對每個 root->next[i] i=[0,26),進行dfs搜索查找最長的單詞
Trie樹結構參考
class Trie//Trie節點 { public:bool isWord;Trie* next[26] = {NULL};Trie():isWord(false){} };class Solution {string ans; public:string longestWord(vector<string>& words) {Trie *root = new Trie();Trie *cur;for(string str : words)//遍歷所有單詞{cur = root;for(char ch : str)//遍歷所有字符{if(cur->next[ch-'a'] == NULL)cur->next[ch-'a'] = new Trie();cur = cur->next[ch-'a'];}cur->isWord = true;//單詞結束標志}string temp;cur = root;int i, j;for(i = 0; i < 26; ++i){temp = "";if(cur->next[i] && cur->next[i]->isWord)//對每個點dfs dfs(cur->next[i], temp, i);}return ans;}void dfs(Trie* root, string &temp, int i){if(!root)return;if(root->isWord)//是結束標志,在字典中{temp.push_back(i+'a');//加入該字符if(temp.size() > ans.size())ans = temp;//更新更長的單詞for(int j = 0; j < 26; ++j)dfs(root->next[j],temp,j);//dfs下一個字符temp.pop_back();//回溯}} };總結
以上是生活随笔為你收集整理的LeetCode 720. 词典中最长的单词(Trie树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1253. 重构 2
- 下一篇: 程序员面试金典 - 面试题 16.03.