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

    class Node {
    public:
        char c;
        bool isWord;
        unordered_map<char,Node*> children;
        Node(char c) {
            this->c = c;
            isWord = false;
        }
    };
    class Trie {
        Node* root;
        
        Node* findString(string s) {
            Node* p = root;
            for (int i = 0; i < s.length(); i++) {
                if (!p->children.count(s[i]))
                    return NULL;
                p = p->children[s[i]];
            }
            return p;
        }
    public:
        /** Initialize your data structure here. */
        Trie() {
            root = new Node(0);
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            Node* p = root;
            for (int i = 0; i < word.length(); i++) {
                if (!p->children.count(word[i]))
                    p->children[word[i]] = new Node(word[i]);
                p = p->children[word[i]];
            }
            p->isWord = true;
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            Node* p = findString(word);
            return p != NULL && p->isWord;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            Node* p = findString(prefix);
            return p != NULL;
        }
    };
    
    /**
     * 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);
     */
  • 相关阅读:
    linux-文件
    字符串函数
    函数
    内存管理
    静态库、动态库文件制作
    Makefile 待完善
    指针
    开发板GEC6816环境搭建,使用VS code
    C语言数组
    连接开发板下载程序
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9065709.html
Copyright © 2011-2022 走看看