码迷,mamicode.com
首页 > 其他好文 > 详细

208. Implement Trie (Prefix Tree)

时间:2017-07-23 10:17:30      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:cal   思考   returns   class   poi   code   sum   initial   any   

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

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


这棵Trie树里存的都是英文小写字母,因此每个Node有26个孩子,代表它的下一个字符a-z。同时,每个节点中,用count记录到这个节点是否是一个endpoint
** 这里没有对Trie树做删除的操作。在查找prefix时,我是判断如果对prefix里的字符一个个遍历,如果节点都不为空,表示存在以Prefix为前缀的字符串。*如果加上删除操作,要确保把Trie里的整条路径删除。
思考:Trie Tree的优缺点有什么?
public class Trie {
    Trie[] children;
    int count = 0;
    /** Initialize your data structure here. */
    public Trie() {
        children = new Trie[26];
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if (word.equals("")) {
            count++;
        }
        Trie cur = this;
        int i = 0;
        while (i < word.length()) {
            if (cur.children[word.charAt(i) - ‘a‘] == null) {
                cur.children[word.charAt(i) - ‘a‘] = new Trie();
            }
            cur = cur.children[word.charAt(i) - ‘a‘];
            i++;
        }
        cur.count++;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie cur = this;
        int i = 0;
        while (cur != null && i < word.length()) {
            cur = cur.children[word.charAt(i) - ‘a‘];
            i++;
        }
        if (cur == null || cur.count == 0) {
            return false;
        }
        return true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie cur = this;
        int i = 0;
        while (cur != null && i < prefix.length()) {
            cur = cur.children[prefix.charAt(i) - ‘a‘];
            i++;
        }
        if (cur == null) {
            return false;
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

 

208. Implement Trie (Prefix Tree)

标签:cal   思考   returns   class   poi   code   sum   initial   any   

原文地址:http://www.cnblogs.com/yuchenkit/p/7223486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!