[Trie树] leetcode 745 Prefix and Suffix Search

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

        使用两个Trie树,分别维护前缀树和后缀树,快速查找到所有满足条件的前缀字符串和后缀字符串,再一一比较同时满足前缀和后缀的(同时出现在两个查找结果中),取下标最大的。

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);
 */

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11298505.html