zoukankan      html  css  js  c++  java
  • LeetCode "Implement Trie (Prefix Tree)"

    Implementation problem.

    class TrieNode {
    public:
        // Initialize your data structure here.
        TrieNode() {
            c = 0;
            bIsLast = false;
        }
        TrieNode(char vc) {
            c = vc;
            bIsLast = false;
        }
    public:
        char c;
        bool bIsLast;
        map<char, TrieNode> childMap;
    };
    
    class Trie {
    public:
        Trie() 
        {
            root = new TrieNode();
        }
        
        ~Trie()
        {
            if (root)
                delete root;
        }
        
        // Inserts a word into the trie.
        void insert(string s) {
            TrieNode *r = root;
            for (int i = 0; i < s.length(); i++)
            {
                if (r->childMap.find(s[i]) == r->childMap.end())
                {
                    r->childMap.insert(make_pair(s[i], TrieNode(s[i])));
                }
                
                r = &(r->childMap[s[i]]);            
            }
            r->bIsLast = true;
        }
    
        // Returns if the word is in the trie.
        bool search(string key) {
            TrieNode *r = root;
            for (int i = 0; i < key.length(); i++)
            {
                if (r->childMap.find(key[i]) == r->childMap.end())
                {
                    return false;
                }
    
                r = &(r->childMap[key[i]]);
            }
    
            return r->bIsLast;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            TrieNode *r = root;
            for (int i = 0; i < prefix.length(); i++)
            {
                if (r->childMap.find(prefix[i]) == r->childMap.end())
                {
                    return false;
                }
    
                r = &(r->childMap[prefix[i]]);
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };
  • 相关阅读:
    遇到的两个问题
    项目分析(map复习)
    while小问题
    二级指针
    映射文件实现进程通信
    struct {0}初始化
    用boost共享内存实现进程通信的例子
    mongo二维数组操作
    项目分析(channelid是如果产生的)
    string为什么可以写入共享内存
  • 原文地址:https://www.cnblogs.com/tonix/p/4500154.html
Copyright © 2011-2022 走看看