472. 连接词

链接:472. 连接词

题解:力扣

class Solution {
private:
    struct TrieTree {
        char c;
        bool end;
        std::string word;
        vector<TrieTree*> next;
        TrieTree() {
            end = false;
            next.resize(26, nullptr);
        }
    };
    TrieTree* _root;
private:
    void insert_trie_tree(const std::string& word) {
        TrieTree* cur = _root;
        for (auto ch : word) {
            if (cur->next[ch-'a'] == nullptr) {
                cur->next[ch-'a'] = new (std::nothrow) TrieTree;
            }
            cur = cur->next[ch-'a'];
        }
        cur->end = true;
        cur->word = word;
    }
    bool find_word(int begin, TrieTree* cur, const std::string& word, std::vector<std::string>& path) {
        if (begin >= word.size()) {
            if (cur == _root && path.size() >= 2) {
                return true;
            }
            return false;
        }
        if (cur->next[word[begin]-'a'] == nullptr) {
            return false;
        }
        cur = cur->next[word[begin]-'a'];
        if (cur->end) {
            path.push_back(cur->word);
            if (find_word(begin+1, _root, word, path)) {
                return true;
            }
            path.pop_back();
        }
        if (find_word(begin+1, cur, word, path)) {
            return true;
        }
        return false;
    }
public:
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        std::vector<std::string> result;
        if (words.size() <= 0) {
            return result;
        }
        _root = new (std::nothrow) TrieTree;
        sort(words.begin(), words.end(), [&](const string & a, const string & b){
            return a.size() < b.size(); 
        });
        for (auto& word : words) {
            int begin = 0;
            std::vector<std::string> path;
            if (word.size() == 0) {
                continue;
            }
            TrieTree* cur = _root;
            if (find_word(begin, cur, word, path)) {
                result.push_back(word);
            } else {
                insert_trie_tree(word);
            }
        }
        return result;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值