0
点赞
收藏
分享

微信扫一扫

leetcode 720题 ———词典最长的单词

捡历史的小木板 2022-03-19 阅读 54
算法

原代码

这道题,找出长度最大和字符最小化的字符串。 因为字符在输入的列表随机排列,所以我们需要对输入的列表排序,然后一边遍历一边将符合条件的字符存入set中(判断条件为截取最后一个字符的子字符串在set中)一边和ans字符串比较。

这样,代码主要的耗时就在排序上面而已。

class Solution {
public:
    string longestWord(vector<string>& words) {
        string ans = "";
        set<string>s;
        sort(words.begin(),words.end());
        for(string word : words){
           int len = word.length();
           if(len == 1){
               if(len>ans.length())ans = word;
               s.insert(word);
            }
           if(s.count(word.substr(0,len-1)) == 1) {
               if(len>ans.length())ans = word;
               s.insert(word);
            }
        }
        return ans;
    }
};

题解代码

我看了题解后又自己写了一次。

方法一

先把所有的子字符串存入set中,然后对字符串进行遍历,满足条件(判断是否自己所有的子字符串都在set当中)。

这种方法和我原方法区别在哪里呢?原方法复杂度主要在排序方面,往后的判断条件只需要判断自己前一个字符串就行,而这个方法判断过程非常耗时,需要对自己的所有子字符串进行遍历

class Solution {
public:
    string longestWord(vector<string>& words) {
        string ans = "";
        set<string>s;
        for(string word:words) s.insert(word);
        for(string word:words){
            int w = word.length();
            int a = ans.length();
            if(w<a||(w == a&&word>ans))continue;
            int i = w-1;
            for(i = w-1;i>0;i--){
                if(s.count(word.substr(0,i)) == 0) break;
            }
            if(i==0)ans = word;
        }
        return ans;
    }
};

方法二

字典树。 这也是一个非常棒的数据结构,将列表中的单词按字符依次存入字典树。 判断的时候直接将树从头部遍历到尾部即可。这里主要的复杂度在于插入和搜索的深度。反正我用了这个数据结构之后,时间和空间都相应增加了

class Trie{
private:
    vector<Trie*>children;
    bool isEnd;
public:
    Trie(){
        children = vector<Trie*>(26,nullptr);
        isEnd = false;
    }

    void insert(string str){
        Trie* node = this;
        for(char s:str){
            int index = s - 'a';
            if(node->children[index]==nullptr){
                node->children[index] = new Trie();
            }
            node = node->children[index];
        }
        node->isEnd = true; 
    }
    bool search(string str){
        Trie* node = this;
        for(char s:str){
            int index = s-'a';
            if(node->children[index]==nullptr||!node->children[index]->isEnd)return false;
            node = node->children[index];
        }
        return node != nullptr&& node->isEnd;
    }
};
class Solution {
public:
    string longestWord(vector<string>& words) {
        Trie trie;
        for(string word:words) trie.insert(word);
        string ans = "";
        for(string word:words){
            if(trie.search(word)){
                if (word.length() > ans.length() || (word.length() == ans.length() && word < ans)) {
                    ans = word;
                }
            }
        }
        return ans;
    }
};

收获

当然是字典树的学习。当然我也得到了这样的经验,以后这类题哈希和字典树都是比较吃香的

传送门

词典最大的单词

举报

相关推荐

0 条评论