leetcode:208. 实现 Trie (前缀树)

leetcode:208. 实现 Trie (前缀树)
概述:
211简化版,简单插入和搜索判断就好

代码:

class Trie {

public:
    
    //定义前缀树结构体
    struct TrieNode{
        bool isEnd = false;
        TrieNode* children[26] = {NULL};
    };
    //构造函数
    Trie(): root(new TrieNode){}
    

    void insert(string word) {
        //从根开始插入
        auto p = root;
        for(int i = 0; i < word.size(); i++){
            int idx = word[i] - 'a';
            if(p->children[idx] == NULL)
                p->children[idx] = new TrieNode;
            p = p->children[idx];
        }
        p->isEnd = true;
    }
    
    bool search(string word) {
        auto p = root;
        for(int i = 0; i < word.size(); i++){
            int idx = word[i] - 'a';
            if(p->children[idx] == NULL) return false;
            p = p->children[idx];
        }
        return p->isEnd;
    }
    
    bool startsWith(string prefix) {
        auto p = root;
        for(int i = 0; i < prefix.size(); i++){
            int idx = prefix[i] - 'a';
            if(p->children[idx] == NULL) return false;
            p = p->children[idx];
        }
        return true;
    }

private:
    TrieNode* root;
};

/**
 * 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);
 */
上一篇:Delphi WMI[3] 获取硬盘ID的方法(无需管理员权限)


下一篇:Delphi 2010 新增功能之: IOUtils 单元(6): TPath(结构体) 的方法与属性