leetcode---Implement Trie (Prefix Tree)---Trie树

Implement a trie with insert, search, and startsWith methods.

 

class TrieNode {
public:
    // Initialize your data structure here.
    bool isLeaf;
    TrieNode *childs[26];
    
    TrieNode() {
        isLeaf = false;
        memset(childs, 0, sizeof(childs));
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        int i = 0;
        int n = word.size();
        TrieNode *p = root;
        while(i < n)
        {
            int j = word[i] - 'a';
            if(p->childs[j] == NULL)
                p->childs[j] = new TrieNode();
            p = p->childs[j];
            i++;
        }
        p->isLeaf = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *p = root;
        int n = word.size();
        if(n == 0)
            return true;
        int i = 0;
        while(i < n)
        {
            int j = word[i] - 'a';
            if(p->childs[j] == NULL)
                return false;
            p = p->childs[j];
            i++;
        }
        return p->isLeaf;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *p = root;
        int n = prefix.size();
        if(n == 0)
            return true;
        int i = 0;
        while(i < n)
        {
            int j = prefix[i] - 'a';
            if(p->childs[j] == NULL)
                return false;
            p = p->childs[j];
            i++;
        }
        return true;
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

 

    原文作者:Trie树
    原文地址: https://blog.csdn.net/u012319493/article/details/53265368
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞