【模板】字典树Trie

Trie 是一颗非典型的多叉树模型,每个节点的分枝数可能有多个

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 c : word){
                if(node -> next[c-'a'] == NULL){
                    node -> next[c-'a'] = new Trie();
                }
                node = node -> next[c-'a'];
            }
            node -> isEnd = true;
        }
        bool search(string word){
            Trie* node = this ;
            for(char c : word){
                node = node -> next[c-'a'];
                if(node == NULL){
                    return false;
                }
            }
            return node -> isEnd;
        }
        bool startWith(string prefix){
            Trie* node = this ;
            for(char c : prefix){
                node = node -> next[c-'a'];
                if(node == NULL)
                    return false;
            }
            return true;
        }
};

 查找词典中最长的单词

给定一个字符串数组words组成的词典,从中找出一个最长的单词,该单词是由字典中其他单词逐步添加一个字母组成的.若其中有多个可行的答案,则返回答案中字典序最小的一个.若无答案,则返回空字符串

本题比较容易看出,采用字典树来解题,

将所有字符插入字典树中之后,循环遍历words数组

若words中的字符串元素每个字符的isEnd 都为真且它最长,与原来的longest进行字符串比较,最终的longest即为所求

class Solution {
public:
    struct Trie{
        bool isEnd;
        Trie* next[26];
        Trie(){
            isEnd = false;
            memset(next,0,sizeof(next));
        }
        void insert(string word){
            Trie* node = this;
            for(char c : word){
                if(node -> next[c-'a'] == NULL){
                    node -> next[c-'a'] = new Trie();
                }
                node = node -> next[c-'a'];
            }
            node -> isEnd = true;
        }
        bool search(string word){
            Trie* node = this;
            for(char c : word){
                if(!node -> next[c-'a']-> isEnd)//判断条件要做修改,下一个如果不是一个单词的结尾直接false;
                    return false;
                node = node ->next[c-'a'];
            }
            return true;
        }
    };
    
    string longestWord(vector<string>& words) {
        Trie trie;
        for(int i = 0 ; i < words.size();i++){
            trie.insert(words[i]);
        }
        string longest;
        for(int i = 0; i < words.size();i++){
            if(trie.search(words[i])){
                if(words[i].length() > longest.length())
                    longest = words[i];
                else if(words[i].length() == longest.length() && words[i] < longest)
                    longest = words[i];
            }
        }
        return longest;
    }
};

 

posted @ 2020-10-12 14:55  我不秃  阅读(142)  评论(0)    收藏  举报