208. Implement Trie (Prefix Tree)

题目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.
Subscribe to see which companies asked this question

class TrieNode {
    boolean isLeaf;
    Map<Character,TrieNode> content;
    // Initialize your data structure here.
    public TrieNode() {
        content = new HashMap<Character,TrieNode>();
    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        if(word == null || word.length() == 0){
            return;
        }
        
        TrieNode node = root;
        TrieNode tempNode = null;;
        for(int i=0, len=word.length(); i<len; i++){
            Character c = word.charAt(i);
            tempNode = node.content.get(c);
            if(tempNode == null){
                tempNode = new TrieNode();
                node.content.put(c,tempNode);
            }
            node = tempNode;
        }
        node.isLeaf = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        if(word == null || word.length() == 0){
            return false;
        }
        
        TrieNode node = root;
        TrieNode tempNode = null;;
        for(int i=0, len=word.length(); i<len; i++){
            Character c = word.charAt(i);
            tempNode = node.content.get(c);
            if(tempNode == null){
                return false;
            }
            node = tempNode;
        }
        return node.isLeaf;
    }

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

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容