Java solution of Implement Trie(Prefix Tree)


  • 1
    V

    class TrieNode {
    char c;
    HashMap<Character, TrieNode> map;
    boolean isLeaf;

    public TrieNode() {
        map = new HashMap<Character, TrieNode>();
        isLeaf = false;
    }
    public TrieNode(char c){
        this.c = c;
        map = new HashMap<Character, TrieNode>();
        isLeaf = false;
    }
    

    }

    public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    
    public void insert(String word) {
        if(word == null || word.length() == 0){
            return;
        }
        
        TrieNode node = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(!node.map.containsKey(c)){
                TrieNode tn = new TrieNode(c);
                node.map.put(c, tn);
            }
            node = node.map.get(c);
            if(i == word.length() - 1){
                node.isLeaf = true;
            }
        }
    }
    
    
    public boolean search(String word) {
        if(word == null || word.length() == 0){
            return true;
        }
        
        TrieNode node = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(!node.map.containsKey(c)){
                return false;
            }else{
                node = node.map.get(c);
            }
        }
        
        if(node.isLeaf){
            return true;
        }
        return false;
    }
    
    
    public boolean startsWith(String prefix) {
         if(prefix == null || prefix.length() == 0){
            return true;
        }
        
        TrieNode node = root;
        for(int i = 0; i < prefix.length(); i++){
            char c = prefix.charAt(i);
            if(!node.map.containsKey(c)){
                return false;
            }else{
                node = node.map.get(c);
            }
        }
        
        
        return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.