LintCode-442: Implement Trie Prefix Tree (System Design题)

  1. Implement Trie (Prefix Tree)
    中文English
    Implement a Trie with insert, search, and startsWith methods.

Example
Example 1:

Input:
insert(“lintcode”)
search(“lint”)
startsWith(“lint”)
Output:
false
true
Example 2:

Input:
insert(“lintcode”)
search(“code”)
startsWith(“lint”)
startsWith(“linterror”)
insert(“linterror”)
search("lintcode“)
startsWith(“linterror”)
Output:
false
true
false
true
true
Notice
You may assume that all inputs are consist of lowercase letters a-z.

经典的Trie设计题。
注意
1)因为都是小写字母,所以节点上不需要map,直接开一个26叉的vector指针数组即可。
2)如果Trie用于字符串检索,那Node上带一个bool表示这个到这个节点有一个完整的word。
如果Trie用于词频统计,那Node上带一个int count 表示该节点代表的单词个数,即当这个节点有一个完整的word时,该count自加1。若该word不存在,插入后该word的count置为1。
另外,这两种场合都可以用hashmap来实现。

class Node {
public:
    Node() : isWord(false) {
        children = vector<Node *>(26, nullptr);
    }

    bool isWord;
    vector<Node*> children;
};

class Trie {
public:
    Trie() {
        root = new Node();
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    void insert(string &word) {
        Node *p = root;
        
        for (int i = 0; i < word.size(); ++i) {
            if (p->children[word[i] - 'a'] == nullptr) {
                p->children[word[i] - 'a'] = new Node();
            }

            p = p->children[word[i] - 'a'];  
        }
        
        p->isWord = true;    
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    bool search(string &word) {
        Node *p = root;
        for (int i = 0; i < word.size(); ++i) {
            if (p->children[word[i] - 'a'] == nullptr)
                return false;
            p = p->children[word[i] - 'a'];    
        }
        
        if (p->isWord) return true;
        else return false;
    }

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    bool startsWith(string &prefix) {
        Node *p = root;
        for (int i = 0; i < prefix.size(); ++i) {
            if (p->children[prefix[i] - 'a'] == nullptr)
                return false;
            p = p->children[prefix[i] - 'a'];    
        }
        return true;       
     }

private: 
    Node* root;
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值