720. 词典中最长的单词

字典序的一道题,主要是了解字典序的含义,以及怎么写自己需要的树的结构。

这道题说的就是要先把单词放入到字典树中然后在遍历一次,并且判断这条分支是不是每一个节点都是true(每一个都是一个单词)

class Trie{
private:
    bool is_string;
    Trie *next[26];
public:
    Trie(){
        is_string = false;
        memset(next,0,sizeof(next));
    }
    void insert(string word){
        Trie *root = this;
        for(const auto& w:word){
            if(root->next[w - 'a'] == nullptr)
                root->next[w - 'a'] = new Trie();
            root = root->next[w - 'a'];
        }
        root->is_string = true;
    }

    bool search(string word){
        Trie *root = this;
        for(const auto& w:word){
            //当节点值存在时,判断该节点是否表示为一个字符串,不是的话,直接返回false,否则继续循环;当节点值不存在时直接返回false
            if(root->next[w-'a']==nullptr||root->next[w-'a']->is_string==false)return false;
            root=root->next[w-'a'];
        }
        return true;
    }
};




class Solution {
public:
    string longestWord(vector<string>& words) {
        if(words.size()==0) return "";
        Trie* root=new Trie();
        for(const auto& word:words)
            root->insert(word);
        string result="";
        for(const auto& word:words){
            if(root->search(word))
            {
                if(word.size()>result.size())result=word;//更新最长单词
                else if(word.size()==result.size()&&word<result)result=word;//长度相等的单词,取字典序小的单词
            }    
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值