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

    Implement a trie with insert, search, and startsWith methods.
    Note:
    You may assume that all inputs are consist of lowercase letters a-z.

    字典树

    class Trie {
    public:
        class node {
          public:
            node* next[26];
            int end;
            node() {
                for (int i = 0; i < 26; ++i) {
                    next[i] = nullptr;
                }
                end = 0;
            }
        };
        /** Initialize your data structure here. */
        node* root;
        Trie() {
            root = new node();
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            if (word.size() == 0) return ;
            node* p = root;
            for (int i = 0; i < word.size(); ++i) {
                int x = word[i] - 'a';
                if (p->next[x] == nullptr) {
                    p->next[x] = new node();
                    p = p->next[x];
                } else {
                    p = p->next[x];
                }
            }
            p->end = 1;        
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            node* p = root;
            for (int i = 0; i < word.size(); ++i) {
                int x = word[i] - 'a';
                if (p->next[x] != nullptr) {
                    p = p->next[x];
                } else {
                    return false;
                }
            }
            if (p->end == 1) return true;
            return false;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            node* p = root;
            for (int i = 0; i < prefix.size(); ++i) {
                int x = prefix[i] - 'a';
                if (p->next[x] != nullptr) {
                    p = p->next[x];
                } else {
                    return false;
                }
            }
            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);
     */
    
  • 相关阅读:
    win查看所有wifi密码
    vsftp配置详解
    python3.7项目打包为一个exe
    ATT&CK实战系列——红队实战(一)
    PHP SECURITY CALENDAR 2017 (Day 9
    python3安装gmpy2
    [CISCN2019 总决赛 Day2 Web1]Easyweb(预期解)
    python2与python3共存及py2IDLE打不开的解决方案
    [BJDCTF 2nd]
    PHP SECURITY CALENDAR 2017 (Day 1
  • 原文地址:https://www.cnblogs.com/pk28/p/7475496.html
Copyright © 2011-2022 走看看