zoukankan      html  css  js  c++  java
  • 字典树

    C++实现trid

    class TrieNode{
    public:
    
        TrieNode():End(false), R(26){
            links.resize(R);
        }
    
        void setEnd(){
            End = true;
        }
    
        bool isEnd(){
            return End;
        }
    
        bool containsKey(char key){
            return links[key - 'a'] != nullptr;
        }
    
        void put(char key, TrieNode* node){
            links[key - 'a'] = node;
        }
    
        TrieNode* get(char key){
            return links[key - 'a'];
        }
    
        private:
            vector<TrieNode*> links;
            bool End;
            int R;
    };
    
    class Trie {
    public:
        /** Initialize your data structure here. */
        TrieNode* root;
        Trie(){
            root = new TrieNode();
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            TrieNode* p = root;
            for(int i = 0; i < word.size(); ++i)
            {
                if(!p->containsKey(word[i]))
                {
                    p->put(word[i], new TrieNode());
                }
                p = p->get(word[i]);
            }
            p->setEnd();
        }
        
        TrieNode* searchPrefix(string word)
        {
            TrieNode* p = root;
            for(int i = 0; i < word.size(); ++i)
            {
                if (p->containsKey(word[i]))
                {
                    p = p->get(word[i]);
                }
                else
                {
                    return nullptr;
                }
            }
            return p;
        }
    
        /** Returns if the word is in the trie. */
        bool search(string word) {
            TrieNode* node = searchPrefix(word);
            return node != nullptr && node->isEnd();
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            TrieNode* node = searchPrefix(prefix);
            return node != nullptr;
        }
    };
    

    参考:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode/

  • 相关阅读:
    jQuery效果
    jQuery事件
    jQuery安装和基础语法
    html5响应式布局
    html5新特性--音频视频,拖放
    js-浏览器DOM
    js-Array
    js-Date
    js-String
    Cocoa touch(五):UIControl
  • 原文地址:https://www.cnblogs.com/qiang-wei/p/12287114.html
Copyright © 2011-2022 走看看