LandscapeMi

landscapemi的博客

leetcode:Trie:Implement Trie (Prefix Tree)(208)

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


class TrieNode {  
public:  
    char var;  
    bool isWord;  
    TrieNode* children[26];  
    // Initialize your data structure here.  
    TrieNode() {  
        var = 0;  
        isWord = false;  
        memset(children, 0x0, sizeof(TreeNode*)*26);  

    }  
    TrieNode(char c){  
        var = c;  
        isWord = false;  
        memset(children, 0x0, sizeof(TreeNode*)*26);  
    }  
};  
class Trie {  
public:  
    Trie() {  
        root = new TrieNode();  
    }  

    // Inserts a word into the trie.  
    void insert(string word) {  
        TrieNode* pNode = root;  
        if (word.length() <= 0)  
        {  
            return;  
        }  
        for (int i= 0; i<word.length(); i++)  
        {  
            char c= word[i];  
            if (pNode->children[c-'a'] == 0)  
            {  
                TrieNode *pNew = new TrieNode(c);  
                pNode->children[c-'a'] = pNew;  
            }  
            pNode = pNode->children[c-'a'];  
        }  
        pNode->isWord = true;  
    }  

    // Returns if the word is in the trie.  
    bool search(string word) {  
        TrieNode *pNode = root;  
        if (word.length() <= 0)  
            return true;  
        for (int i =0; i<word.length(); i++)  
        {  
            char c = word[i];  
            pNode = pNode->children[c-'a'];  
            if (pNode == NULL)  
                return false;  
        }  
        return pNode->isWord;  
    }  

    // Returns if there is any word in the trie  
    // that starts with the given prefix.  
    bool startsWith(string prefix) {  
        TrieNode *pNode = root;  
        if (prefix.length()<=0)  
            return true;  
        for (int i=0; i<prefix.length(); i++)  
        {  
            char c = prefix[i];  
            pNode = pNode->children[c-'a'];  
            if (pNode == NULL)  
                return false;  
        }  
        return true;  
    }  
    void freeTrieNode(TrieNode* pNode){  
        if (pNode == NULL)  
            return;  
        for (int i=0; i<26;i++)  
        {  
            TrieNode* pChild = pNode->children[i];  
            if (pChild != NULL)  
            {  
                freeTrieNode(pChild);  
            }  
        }  
        free(pNode);  
    }  
    ~Trie(){  
        freeTrieNode(root);  
    }  
private:  
    TrieNode* root;  
};  
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52385239
个人分类: leetcode(c++)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

leetcode:Trie:Implement Trie (Prefix Tree)(208)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭