LeetCode 720. 词典中最长的单词

题目描述

720. 词典中最长的单词

解法:打表

我们先把 words 按照单词长度进行排序,长度相同的按照题目要求按照字典序进行排序,最终 words 能保证我们在遍历的过程中可以每一步都是当前最长、字典序最小的单词

如果当前遍历到的单词删除最后一个字母在表中可以查找到,那么说明当前这个单词是符合题目答案的要求,那么就可以更新答案,将其插入到表中

class Solution {
public:
    string longestWord(vector<string>& words) {
        sort(words.begin(), words.end(), [](const string& a, const string& b){
            return a.size() != b.size() ? a.size() < b.size() : a>b;
        });
        string ans;
        unordered_set<string> candidates = {""};
        for (auto word: words)
        {
            if (candidates.count(word.substr(0, word.size() - 1)))
            {
                candidates.emplace(word);
                ans = word;
            }
        }
        return ans;
    }
};

解法二:字典树

这道题在字典树的基础上修改一下 search 方法就可以得到:起始时,我们将所有的 word 插入到字典树中,那么每个符合题目要求的候选答案其前缀结点必定满足 isEnd = true,接下来比较长度和字典序得到最长的词即可

class Trie {
private:
    bool isEnd;
    Trie* next[26];

public:
    /** Initialize your data structure here. */
    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node = this;
        for(auto c: word)
        {
            if(node->next[c-'a']==NULL) node->next[c-'a'] = new Trie();
            node  = node->next[c-'a'];
        }
        node->isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node = this;
        for(auto c: word)
        {
            node = node->next[c-'a'];
            if(node==NULL || !node->isEnd) return false;
        }
        return node->isEnd;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值