[leetcode] 208. Implement Trie (Prefix Tree) 解题报告

来源:互联网 发布:期货行情数据接口 编辑:程序博客网 时间:2024/06/05 22:39

题目链接: https://leetcode.com/problems/implement-trie-prefix-tree/

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.


思路: 字典树的原理从每一个结点可以往下生长26个结点, 代表从一个字符下一个字符的情况, 所以字典树的每一个树的子树数量将不再是二叉树的左右两个结点, 而是26子树. 另外我们需要在每一个结点上有另外一个标记, 代表到当前结点的路径是否构成一个单词. 这样当很多的单词共享一些前缀和路径的时候, 我们可以知道到哪里是一个单词.

这题没有正则匹配, 所以比较简单一些.

代码比较容易理解, 如下:

class TrieNode {public:    // Initialize your data structure here.    TrieNode():child(vector<TrieNode*>(26, NULL)), isWord(false) {    }    vector<TrieNode*> child;    bool isWord;};class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode* tem = root;        for(auto ch: word)        {            if(tem->child[ch-'a'] == NULL)                tem->child[ch-'a'] = new TrieNode();            tem = tem->child[ch-'a'];        }        tem->isWord = true;    }        // Returns if the word is in the trie.    bool search(string word) {        TrieNode* tem = root;        for(auto ch: word)        {            if(tem->child[ch-'a'] == NULL)                 return false;            tem = tem->child[ch-'a'];        }        return tem->isWord;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode* tem = root;        for(auto ch: prefix)        {            if(tem->child[ch-'a'] == NULL)                 return false;            tem = tem->child[ch-'a'];        }        return true;    }private:    TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");


0 0