[Trie树] leetcode 745 Prefix and Suffix Search

problem:https://leetcode.com/problems/prefix-and-suffix-search/

        Trie two trees, respectively, to maintain the prefix and suffix tree tree, quickly find the string prefix and suffix strings to satisfy all the conditions, and then compared one by one while meeting prefixes and suffixes (present in both lookup results), remove the standard maximum.

class WordFilter {
    struct Trie
    {
        char ch;
        bool bWord = false;
        unordered_map<char,Trie*> childs;     
        Trie(char c) : ch(c) { }
        Trie() { }
    };
public:
    Trie* begin = nullptr;
    Trie* end = nullptr;
    unordered_map<string, int> index;
    void Insert(Trie*& cur, char ch, bool bWord)
    {
        if(cur->childs.find(ch) == cur->childs.end())
        {
            cur->childs[ch] = new Trie(ch);
        }
        cur = cur->childs[ch];
        if(bWord) cur->bWord = true;
    }
        
    void Get(Trie* cur, vector<string>& res, string str)
    {
        if(cur->bWord)
        {
            res.push_back(str);
        }
        for(auto& child : cur->childs)
        {
            Get(child.second, res, str + child.first);
        }
    }
    void Find(Trie* cur, vector<string>& res, const string& word)
    {
        for(int i = 0;i < word.size();i++)
        {
            if(cur->childs.find(word[i]) == cur->childs.end())
            {
                return;
            }
            else
            {
                cur = cur->childs[word[i]];
            }
        }
        return Get(cur, res, word);
    }
    
    WordFilter(vector<string>& words) {
        begin = new Trie();
        end = new Trie();
        int count = 0;
        for(auto& word : words)
        {
            index[word] = count++;
            Trie* cur = begin;
            for(int i = 0;i < word.size();i++)
            {
                Insert(cur, word[i], i == word.size() - 1);
            }
            cur = end;
            for(int i = word.size() - 1; i >= 0;i--)
            {
                Insert(cur, word[i], i == 0);
            }            
        }
    }

    int f(string prefix, string suffix) {
        vector<string> preStr;
        vector<string> sufStr;
        reverse(suffix.begin(), suffix.end());
        Find(begin, preStr, prefix);
        Find(end,   sufStr, suffix);
        for(auto& suf : sufStr)
        {
            reverse(suf.begin(),suf.end());
        }
        int res = -1;
        for(auto& pre : preStr)
        {
          
            for(auto& suf : sufStr)
            {
                if(pre == suf)
                {
                    res = max(res,index[pre]);
                }
            }
        }
        return res;
    }
};

/**
 * Your WordFilter object will be instantiated and called as such:
 * WordFilter* obj = new WordFilter(words);
 * int param_1 = obj->f(prefix,suffix);
 */

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11298505.html