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

     

  • 相关阅读:
    Linux Process Memory Usage
    ezwinports
    Linux程序调试查看二进制文件
    Build tcpdump for ARM
    Tomcat start/stop script
    Apache+PHP+MySQL
    查看安装的glibc版本
    CodeMirror
    GeSHi Generic Syntax Highlighter
    C++命令行解析库
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171433.html
Copyright © 2011-2022 走看看