leetcode-每日一题2022.3.17 词典中最长的单词

题目

力扣

思路 模拟

先把words中的字符串放到哈希表里,再遍历words的每一个字符串,判断它从0开始的每一个子串是否存在于哈希表里。

代码

class Solution {
public:
    string longestWord(vector<string>& words) {
        int ans = -1;
        unordered_set<string> set;
        for(string word : words)
            set.insert(word);
        for(int i = 0; i < words.size(); i++){
            if(ans == -1 || words[ans].size() < words[i].size() || (words[ans].size() == words[i].size() && words[ans] > words[i])){
                bool flag = true;
                for(int j = 1; j < words[i].size(); j++){
                    if(set.count(words[i].substr(0,j)) == 0)
                        flag = false;
                }
                if(flag) ans = i;
            }
        }
        return ans == -1 ? "" : words[ans];
    }
};

思路 字典树

定义字典树数据结构,并定义insert和search方法,如果符合条件,每一位的isEnd都要是true才可以。

代码

class Trie{
private:
    bool isEnd;
    Trie* next[26];
public:
    Trie(){
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
    void insert(string word){
        Trie* node = this;
        for(char ch : word){
            if(node -> next[ch - 'a'] == nullptr){
                node -> next[ch - 'a'] = new Trie();
            }
            node = node -> next[ch - 'a'];
        }
        node -> isEnd = true;
    }

    bool search(string word){
        Trie* node = this;
        bool ans = false;
        for(char ch : word){
            node = node -> next[ch - 'a'];
            if(node -> isEnd == false)
                return false;
        }
        return true;
    }
};

class Solution {
public:
    string longestWord(vector<string>& words) {
        string ans = "";
        Trie* trie = new Trie();
        for(string word : words)
            trie -> insert(word);
        for(string word : words){
            if(ans.size() < word.size() || (ans.size() == word.size() && ans > word)){
                if(trie -> search(word))
                    ans = word;
            }
        }
        return ans;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值