208. Implement Trie (Prefix Tree)

来源:互联网 发布:java 国家法定节假日 编辑:程序博客网 时间:2024/05/17 04:14

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

class TrieNode {public:    // Initialize your data structure here.    bool isLeaf;    TrieNode *node[26];    TrieNode() {        for(int i=0;i<26;i++)        node[i]=0;        isLeaf=false;    }};class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode *now=root;        for(int i=0;i<word.length();i++)        {            int c=word[i]-'a';            if(now->node[c]==0)            now->node[c]=new TrieNode();            now=now->node[c];        }        now->isLeaf=true;    }    // Returns if the word is in the trie.    bool search(string word) {        TrieNode *now=root;        for(int i=0;i<word.length();i++)        {            int c=word[i]-'a';            if(now->node[c]==0)            return false;            now=now->node[c];        }        return now&&now->isLeaf;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode *now=root;        for(int i=0;i<prefix.length();i++)        {            int c=prefix[i]-'a';            if(now->node[c]==0)            return false;            now=now->node[c];        }        return now;    }private:    TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");


0 0
原创粉丝点击