Leetcode 208. Implement Trie (Prefix Tree)

来源:互联网 发布:日本男生发型 知乎 编辑:程序博客网 时间:2024/06/05 16:57

Implement a trie with insert, search, and startsWith methods.

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

s思路:
1. trie,前缀树。用来搜索string很方便快速。每个节点包括26个指针数组,对应26个字母,如果child[0]不为空,表示这个字母存在,否则没这个字符;还有是否是单词结尾的标志符。
2. 如何insert? 需要对单词从左往右dfs遍历,比如:”bat”,首先看trie根节点指向的26个child的child[1]是否存在(不存在,用NULL表示),存在就进入下一个层次,不存在则需要新建一个node,并让child[1]指向这个节点。
3. 如何搜索?搜索和insert很类似,都是通过dfs一层一层的往下找,某个位置如果没指针,表示没找到;最后位置如果没有isWord表示也没有。这里就显示单词结尾符号的用处了!
4. 如何startswith?比如:查找是否含有以ab开头的单词。也是搜索,不过不需要判断单词结尾即可!

struct node{    node* child[26];    bool isWord;    node(){        for(int i=0;i<26;i++)            child[i]=NULL;        isWord=false;       } };class Trie {private:    node* root;public:    /** Initialize your data structure here. */    Trie() {        root=new node();    }    /** Inserts a word into the trie. */    void insert(string word) {        node* cur=root;        for(int i=0;i<word.size();i++){            int idx=word[i]-'a';            if(!cur->child[idx]){//没有这个字母                cur->child[idx]=new node();            }            cur=cur->child[idx];        }        cur->isWord=true;    }    /** Returns if the word is in the trie. */    bool search(string word) {        node* cur=root;        for(int i=0;i<word.size();i++){            int idx=word[i]-'a';            if(!cur->child[idx]){//没有这个字母                return false;            }            cur=cur->child[idx];        }        return cur->isWord;    }    /** Returns if there is any word in the trie that starts with the given prefix. */    bool startsWith(string prefix) {        node* cur=root;        for(int i=0;i<prefix.size();i++){            int idx=prefix[i]-'a';            if(!cur->child[idx]){//没有这个字母                return false;            }            cur=cur->child[idx];        }        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); */
0 0
原创粉丝点击