关闭

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

44人阅读 评论(0) 收藏 举报
分类:

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;  
};  
0
0

猜你在找
【直播】计算机视觉原理及实战—屈教授
【套餐】深度学习入门视频课程—唐宇迪
【套餐】Hadoop生态系统零基础入门--侯勇蛟
【套餐】嵌入式Linux C编程基础--朱有鹏
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】机器学习之凸优化——马博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:102200次
    • 积分:6682
    • 等级:
    • 排名:第3493名
    • 原创:589篇
    • 转载:2篇
    • 译文:0篇
    • 评论:2条
    最新评论