Skip to content

Latest commit

 

History

History
66 lines (60 loc) · 1.63 KB

208. Implement Trie (Prefix Tree).md

File metadata and controls

66 lines (60 loc) · 1.63 KB

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

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings.

class TrieNode{
    public Map<Character,TrieNode> map=new HashMap<>();
    public boolean isEnd=false;
    public void putChildIfAbsent(char ch){
        map.putIfAbsent(ch,new TrieNode());
    }
    public TrieNode getChild(char ch){
        return map.get(ch);
    }
}
class Trie {
    TrieNode root = new TrieNode();
    public void insert(String word) {
        TrieNode curr=root;
        for(char ch:word.toCharArray()){
            curr.putChildIfAbsent(ch);
            curr=curr.getChild(ch);
        }
        curr.isEnd=true;
    }
    
    public boolean search(String word) {
        TrieNode curr=root;
        for(char ch:word.toCharArray()){
            curr=curr.getChild(ch);
            if(curr==null) return false;
        }
        return curr.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode curr=root;
        for(char ch:prefix.toCharArray()){
            curr=curr.getChild(ch);
            if(curr==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);
 */