鱼C论坛

 找回密码
 立即注册
查看: 1955|回复: 1

[技术交流] C++刷LeetCode(720. 词典中最长的单词)【字典树】【深度优先搜索】

[复制链接]
发表于 2020-12-19 16:38:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

  2. 若无答案,则返回空字符串。

  3.  

  4. 示例 1:

  5. 输入:
  6. words = ["w","wo","wor","worl", "world"]
  7. 输出:"world"
  8. 解释:
  9. 单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
  10. 示例 2:

  11. 输入:
  12. words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
  13. 输出:"apple"
  14. 解释:
  15. "apply"和"apple"都能由词典中的单词组成。但是"apple"的字典序小于"apply"。
  16.  

  17. 提示:

  18. 所有输入的字符串都只包含小写字母。
  19. words数组长度范围为[1,1000]。
  20. words[i]的长度范围为[1,30]。

  21. 来源:力扣(LeetCode)
  22. 链接:https://leetcode-cn.com/problems/longest-word-in-dictionary
  23. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     struct TrieTree{
  4.         bool flag;
  5.         map<char, TrieTree*>next;
  6.         TrieTree():flag(false){};
  7.     };
  8.     void dfs(TrieTree* cur_node, string&res, string temp){
  9.         if(cur_node == NULL ||cur_node -> flag == false)return;
  10.         if(temp.size() > res.size())res = temp;  
  11.         for(auto cha : cur_node -> next){
  12.             dfs(cur_node -> next[cha.first], res, temp + cha.first);
  13.         }
  14.     }
  15.     string longestWord(vector<string>& words) {
  16.         //构建字典树
  17.         TrieTree* root = new TrieTree();
  18.         for(auto word : words){
  19.             TrieTree* node = root;
  20.             for(auto cha : word){
  21.                 if((node -> next).count(cha) == 0){
  22.                     node -> next[cha] = new TrieTree();
  23.                 }
  24.                 node = node -> next[cha];
  25.             }
  26.             node -> flag = true;
  27.         }
  28.         //深度优先搜索
  29.         string res;
  30.         for(auto cha : root ->next){
  31.             if(root -> next[cha.first] -> flag == true){
  32.                 string temp;
  33.                 dfs(root -> next[cha.first], res, temp + cha.first);
  34.             }
  35.         }
  36.         return res;
  37.     }
  38. };
复制代码

评分

参与人数 1荣誉 +5 贡献 +3 收起 理由
昨非 + 5 + 3

查看全部评分

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-12-19 16:39:24 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-7 13:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表