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);
     */
    
  • 相关阅读:
    POJ 1363
    HDU 1251(trie树)
    POJ 2081
    NYOJ 3(多边形重心)
    电子琴源码
    POJ 2503
    推荐些在线小制作小工具
    C# 在 webBrowser 光标处插入 html代码 .
    IIS自动安装程序(免费)
    developer express右键菜单显示汉化
  • 原文地址:https://www.cnblogs.com/pk28/p/7475496.html
Copyright © 2011-2022 走看看