面试题 17.15. 最长单词

. - 力扣(LeetCode)

class Solution {
public:
struct Trie {
    Trie() {
        end = false;
        next.resize(26, nullptr);
    }
    bool end;
    std::vector<Trie*> next;
};
    void insert_trie(Trie* root, std::string& word) {
        Trie* cur = root;
        for (int i = 0; i < word.size(); ++i) {
            if (!cur->next[word[i]-'a']) {
                cur->next[word[i]-'a'] = new (std::nothrow) Trie;
            }
            cur = cur->next[word[i]-'a'];
        }
        cur->end = true;
    }
    string longestWord(vector<string>& words) {
        if (words.size() <= 0) {
            return "";
        }
        Trie* root = new (std::nothrow) Trie;
        for (auto& word : words) {
            insert_trie(root, word);
        }
        // 如果长度相等,按照字典序列排序
        // 否则按照长度排序
        sort(words.begin(), words.end(), [](std::string& w1, std::string& w2) {
            if (w1.size() == w2.size()) {
                return w1 < w2;
            }
            return w1.size() > w2.size();
        });
        
        for (auto& word : words) {
            // false表示排出为自己的字符串
            if (can_split(false, word, root)) {
                return word;
            }
        }
        return "";
    }
private:
    bool can_split(bool flag, std::string word, Trie* root) {
        Trie* cur = root;
        for (int i = 0; i < word.size(); ++i) {
            // 如果没有这个字符
            if (!cur->next[word[i]-'a']) {
                return false;
            }
            /*if (cur->next[word[i]-'a']->end && i == word.size()-1 && flag) {
                return true;
            }*/
            // 这个字符是结尾,则尝试一下
            if (cur->next[word[i]-'a']->end && can_split(true, word.substr(i+1), root)) {
                return true;
            }
            cur = cur->next[word[i]-'a'];
       }
       // 判断是否已经到了字符串的末尾
       return flag && cur->end;
       //return false;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值