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

来源:互联网 发布:VB中input函数怎么用 编辑:程序博客网 时间:2024/05/30 05:00

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");


 

0 0
原创粉丝点击