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

208. Implement Trie (Prefix Tree)

时间:2016-05-30 08:48:16      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

Implement a trie with insertsearch, and startsWith methods.

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

 

Subscribe to see which companies asked this question

Hide Tags
 Design Trie

 

class TrieNode {
    
    public HashMap<Character, TrieNode> children = new HashMap<>();
    public boolean exist = false;
    
    public TrieNode() {
        
    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode r = root;
        for(int i = 0; i<word.length(); ++i)
        {
            Character c = word.charAt(i);
            TrieNode child = r.children.get(c);
            if(child == null)
            {
                child = new TrieNode();
                r.children.put(c, child);
            }
            r = child;
        }
        r.exist = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode r = root;
        for(int i = 0; i<word.length(); ++i)
        {
            Character c = word.charAt(i);
            TrieNode child = r.children.get(c);
            if(child == null)
                return false;
            r = child;
        }
        return r.exist;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode r = root;
        for(int i = 0; i<prefix.length(); ++i)
        {
            Character c = prefix.charAt(i);
            TrieNode child = r.children.get(c);
            if(child == null)
                return false;
            r = child;
        }
        return true;
    }
}

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

 

208. Implement Trie (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5541081.html

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