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;
    };
  • 相关阅读:
    喜欢这效果
    jQuery.Validate 使用例子
    网站安全要略谨记
    asp.net发送邮件
    URL参数的加号等特殊字符的处理
    sqlhelper
    Python单元测试框架
    基于Selenium2与Python自动化测试环境搭建
    Robot Framework和Selenium 2 Grid集成指南
    APP性能测试(CPU)
  • 原文地址:https://www.cnblogs.com/tonix/p/4500154.html
Copyright © 2011-2022 走看看