LeetCode 720. 词典中最长的单词 (字典树的简单应用)

词典中最长的单词
① 首先把n的字符串插入字典树
② 然后依次查询n的字符串是否满足要求——它的每个字符都是某个字符串的结尾。

class Solution {
    string ans = "";
    struct Node{   
        bool isEnd = false;
        Node* children[26] = {0};
    };
    Node* root = new Node;

    void insert(const string &s){
        Node* p = root;
        for(char c:s){
            if(!p->children[c-'a']){
                p->children[c-'a'] = new Node;
            }
            p = p->children[c-'a'];
        }
        p->isEnd = true;
    }

    bool find(const string &s){
        Node* p = root;
        for(char c:s){
            if(!p->children[c-'a']  || !p->children[c-'a']->isEnd){
                return false;
            }
            p = p->children[c-'a'];
        }
        return true;
    }

public:
    string longestWord(vector<string>& words) {
        for(string &s:words){
            insert(s);
        }
        for(string &s:words){
            if(find(s)){

                if(s.size()>ans.size()){
                    ans = s;
                }else if(s.size()==ans.size()){
                    ans = min(ans,s);
                }
            }
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章