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

Implement Trie (Prefix Tree)

时间:2015-05-08 22:05:17      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode   trie   递归   prefix   

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

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

思路:
之前也没有接触过Trie,百科上查了一下,大概就是词源的问题,N个word有公共前缀,只是后缀不同,可以用树表示。
可以通过递归解决。

代码如下:

class TrieNode {
    // 应该都是private的;只是为了减少代码量
    // Initialize your data structure here.
    public Map<Character,TrieNode> map;//存放后缀
    public char val;//当前节点的字符值
    public boolean tail;//一个字符串以该节点结尾
    public TrieNode() {
        map = new HashMap<>();
        tail=false;
    }
    public TrieNode(char c) {
        map = new HashMap<>();
        this.val=c;
        tail=false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        insert(root,word);
    }

    private void insert(TrieNode root,String word){
        if(word.length()==0){
            root.tail=true;
            return;
        }
        TrieNode cur=root;
        char c=word.charAt(0);
        if(cur.map.containsKey(c)){
            TrieNode child = cur.map.get(c);
            insert(child,word.substring(1));
        }else{
            TrieNode child = new TrieNode(c);
            cur.map.put(c,child);
            insert(child,word.substring(1));
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        return search(root,word);
    }

    private boolean search(TrieNode root,String word){
        if(word.length()==0)
            return root.tail==true;
        char c = word.charAt(0);
        if(!root.map.containsKey(c))
            return false;
        TrieNode child = root.map.get(c);
        return search(child,word.substring(1));
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
         return startsWith(root,prefix);
    }

    private boolean startsWith(TrieNode root,String prefix) {
        if(prefix.length()==0)
            return true;
        char c = prefix.charAt(0);
        if(!root.map.containsKey(c))
            return false;
        TrieNode child = root.map.get(c);
        return startsWith(child,prefix.substring(1));
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

Implement Trie (Prefix Tree)

标签:leetcode   trie   递归   prefix   

原文地址:http://blog.csdn.net/u010786672/article/details/45585269

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