Leetcode 208. Implement Trie (Prefix Tree)

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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值