zoukankan      html  css  js  c++  java
  • 【刷题-LeetCode】208. Implement Trie (Prefix Tree)

    1. Implement Trie (Prefix Tree)

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

    Example:

    Trie trie = new Trie();
    
    trie.insert("apple");
    trie.search("apple");   // returns true
    trie.search("app");     // returns false
    trie.startsWith("app"); // returns true
    trie.insert("app");   
    trie.search("app");     // returns true
    

    Note:

    • You may assume that all inputs are consist of lowercase letters a-z.
    • All inputs are guaranteed to be non-empty strings.

    class trie_node{
    public:
        vector<trie_node*>child; // 根据当前字符选取下一个节点,如果当前字符是a,接下来就往child['a']的分支走
        bool isWord; // 表明到达该节点时,是否包含了一个完整的单词
        // 构造函数
        trie_node(): isWord(false), child(26, NULL){}
        // 析构函数
        ~trie_node(){
            for(auto &c : child)delete c;
        }
    };
    class Trie {
    public:
        trie_node* root;
        /** Initialize your data structure here. */
        // 构造函数
        Trie() {
            root = new trie_node();
        }
        /** Inserts a word into the trie. */
        void insert(string word) {
            trie_node *cur = root;
            for(int i = 0; i < word.size(); ++i){
                int idx = word[i] - 'a';
                if(cur->child[idx] == NULL){
                    cur->child[idx] = new trie_node();
                }
                cur = cur->child[idx];
            }
            cur->isWord = true;
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            trie_node *cur = root;
            for(auto ch : word){
                int idx = ch - 'a';
                if(cur->child[idx] == NULL)return false;
                cur = cur->child[idx];
            }
            return cur->isWord;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            trie_node *cur = root;
            for(auto ch : prefix){
                int idx = ch - 'a';
                if(cur->child[idx] == NULL)return false;
                cur = cur->child[idx];
            }
            return true;
        }
    };
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie* obj = new Trie();
     * obj->insert(word);
     * bool param_2 = obj->search(word);
     * bool param_3 = obj->startsWith(prefix);
     */
    
  • 相关阅读:
    网页内容自动换行
    问题:Sql Server登录不进去的问题
    Truncate的用法
    SQL当前日期获取技巧
    .NET导出Excel遇到的80070005错误的解决
    养眼方式
    在页面里显示出PPT的效果
    问题(待解决):运行NCover产生的问题
    用CSS控制输入框输入的字母自动转入都是大写字母
    问题:Default引起的问题
  • 原文地址:https://www.cnblogs.com/vinnson/p/13322634.html
Copyright © 2011-2022 走看看