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);
     */
  • 相关阅读:
    关于《哈利波特》书的购买方案
    你的灯亮着吗读后感三
    jmeter做接口测试
    jmeter的分布式部署
    JMeter的定时器
    我的功能测试用例是怎么写
    常见的功能测试检查点
    测试用例概论
    敏捷开发与迭代开发
    软件测试模型
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9065709.html
Copyright © 2011-2022 走看看