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

    Trie 树实现

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

    class TrieNode {
    public:
        // Initialize your data structure here.
    
        TrieNode *child[26];
        bool isWord;
        TrieNode():isWord(false){
            for(auto &a : child)
                a = nullptr;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        void insert(string word) {
            TrieNode* p = root;
            for(auto &a : word){
                int i = a - 'a';
                if(!p->child[i]) p->child[i] = new TrieNode();
                p = p->child[i];
            }
            p->isWord = true;
        }
    
        // Returns if the word is in the trie.
        bool search(string word) {
            TrieNode* p = root;
            for(auto &a : word){
                int i = a - 'a';
                if(!p->child[i]) return false;
                p = p->child[i];
            }
            return p->isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            TrieNode* p = root;
            for(auto &a : prefix){
                int i = a - 'a';
                if(!p->child[i]) return false;
                p = p->child[i];
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };

    参看:http://www.cnblogs.com/grandyang/p/4491665.html

     

  • 相关阅读:
    懒加载 和 json
    [iOS]用instancetype代替id作返回类型有什么好处?
    (转)Objective-C语法之KVC使用
    UITableView 展示数据
    shopee
    防火墙
    vue项目开发技巧
    文件流
    vant
    node 使用
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171433.html
Copyright © 2011-2022 走看看