實現字典樹 Trie 的基本操作

實現字典樹 Trie 的基本操作

字典樹可以快速的匹配多個字符串的共同前綴,
在這裏插入圖片描述
下面是一些字典樹常見的應用:
在這裏插入圖片描述
在這裏插入圖片描述
trie可以看做是一個多叉樹,在每個結點中存放了必要的信息,對所傳入的參數進行快速的判讀

class trieNode{
public:
    shared_ptr<trieNode> next[26];
    bool is_word;
    char value;
    trieNode() = default;
    trieNode(char ch):is_word(false),value(ch){}
};
class Trie {
private:
//    trieNode *root;
    shared_ptr<trieNode> root;
public:
    /** Initialize your data structure here. */
    Trie() {

        root = std::make_shared<trieNode>();
        root->value = ' ';
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        shared_ptr<trieNode> ws = root;
        for(int i=0;i<word.size();++i){
            char c = word.at(i);
            if(ws->next[c-'a'] == nullptr){
                ws->next[c-'a'] = std::make_shared<trieNode>(c);
            }
            ws = ws->next[c-'a'];
        }
        ws->is_word = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        shared_ptr<trieNode> ws = root;
        for(int i=0;i<word.size();++i){
            char c = word.at(i);
            if(ws->next[c-'a'] == nullptr)
                return false;
            ws = ws->next[c-'a'];
        }
        return ws->is_word;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        shared_ptr<trieNode> ws = root;
        for(int i=0;i<prefix.size();++i){
            char c = prefix.at(i);
            if(ws->next[c-'a'] == nullptr) return false;
            ws = ws->next[c-'a'];
        }
        return true;
    }
};
/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章