zoukankan      html  css  js  c++  java
  • LeetCode 720. 词典中最长的单词

    思路

    先将所有单词存入字典树。对于每个单词,在字典树中检查它的全部前缀是否存在。

    代码实现

     1 class Solution {
     2 
     3     class Trie {
     4     public:
     5         bool isWord = false;
     6         Trie* next[26] = {NULL};
     7 
     8         Trie(){}
     9         void insert(const string& word) {
    10             Trie* t = this;
    11             for(int i = 0; i < word.length(); ++i){
    12                 if(t->next[word[i]-'a'] == NULL) {
    13                     t->next[word[i]-'a'] = new Trie();
    14                 }
    15 
    16                 t = t->next[word[i]-'a'];
    17             }
    18 
    19             t->isWord = true;
    20         }
    21 
    22         //检查word单词的所有前缀是否都在字典树中
    23         bool check(const string& word) {
    24             Trie* t = this;
    25             for(int i = 0; i < word.length(); ++i){
    26                 if(t->next[word[i]-'a']->isWord == false) {
    27                     return false;
    28                 }
    29                 t = t->next[word[i]-'a'];
    30             }
    31             return true; 
    32         }
    33         
    34     };
    35     
    36 public:
    37     string longestWord(vector<string>& words) {
    38         Trie* t = new Trie();
    39         for(int i = 0; i < words.size(); ++i) {
    40             t->insert(words[i]);
    41         }
    42 
    43         string ans = "";
    44         for(int i = 0; i < words.size(); ++i) {
    45             if(t->check(words[i]) == true) {
    46                 if(words[i].length() > ans.length())
    47                     ans = words[i];
    48                 else if(words[i].length() == ans.length() && words[i] < ans)
    49                     ans = words[i];
    50             }
    51         }
    52 
    53         return ans;
    54     }
    55 };

    复杂度分析

    时间复杂度:O(所有单词长度之和),即创建前缀树占主要。

    空间复杂度:O(所有单词长度之和),创建前缀树耗费的空间。

  • 相关阅读:
    技术选型总结
    这些年来收集的好用的好玩的软件,强烈推荐给大家
    如何解决markdown中图片上传的问题
    01.如何把.py文件打包成为exe,重点讲解pyinstaller的用法
    Asp.net中汉字转换成为拼音
    程序员常用网址收集
    通过IP来判断所在城市
    以太坊
    分布式系统领域经典论文翻译集
    T50
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/13836466.html
Copyright © 2011-2022 走看看