LintCode 442:Implement Trie

来源:互联网 发布:js自定义全局函数 编辑:程序博客网 时间:2024/06/06 01:46
class TrieNode {public:    // Initialize your data structure here.    TrieNode* children[26];    bool flag;//check if it's the end of a word.    TrieNode() :flag(0){        for(int i=0;i<26;i++)            children[i]=NULL;    }};class Trie {    TrieNode* insertNode(char tmp,TrieNode* parent){        int index=tmp-97;        if(!parent->children[index])            parent->children[index]=new TrieNode();        return parent->children[index];    }    int ifStartWith(string word){        char c=word[0];        int index=c-97;        int stringLength=word.length();        int i;        TrieNode* child;        if(!root->children[index])            return 0;        else            child=root->children[index];        for(i=1;i<stringLength;i++){            index=word[i]-97;            if(!child->children[index])                return 0;            child=child->children[index];        }        if(child->flag)            return 1;//exists the word;        else            return -1;//only exists the subword.    }public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        int stringLength=word.length();        if(!stringLength)            return;        int i;        TrieNode* child=insertNode(word[0],root);        for(i=1;i<stringLength;i++){            child=insertNode(word[i],child);        }        child->flag=1;    }    // Returns if the word is in the trie.    bool search(string word) {        if(ifStartWith(word)==1)            return 1;        return 0;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        if(ifStartWith(prefix))            return 1;        return 0;    }private:    TrieNode* root;};

0 0
原创粉丝点击