Clean java solution


  • 1
    L

    class TrieNode {
    // Initialize your data structure here.
    //https://leetcode.com/discuss/34838/java-implementation-use-trienode-26-to-store-children-nodes
    private Map<Character, TrieNode> children;
    private boolean endOfWord;
    public TrieNode() {
    children = new HashMap<Character, TrieNode>();
    endOfWord = false;
    }

    public boolean getEndOfWord(){
        return endOfWord;
    }
    
    public void setEndOfWord(){
        endOfWord = true;
    }
    
    public void insert(String word){
        if(word == null || word.equals("")){
            return;
        }
        
        TrieNode node = this;
        for(int i = 0; i < word.length(); i++){
            char visiting = word.charAt(i);
            if(!node.children.containsKey(visiting)){
                node.children.put(visiting, new TrieNode());
            }
            
            node = node.children.get(visiting);
        }
        
        node.setEndOfWord();
    }
    
    
    public boolean search(String word){
       TrieNode node = find(word);
       return node != null && node.getEndOfWord();
    }
    
    public boolean startsWith(String prefix){
       TrieNode node = find(prefix);
       return node != null;
    }
    
    
    private TrieNode find(String target){
        if(target == null || target.equals("")){
            return null;
        }
        
        TrieNode node = this;
        for(int i = 0; i < target.length(); i++){
            char visiting = target.charAt(i);
            if(!node.children.containsKey(visiting)){
                return null;
            }
            
            node = node.children.get(visiting);
        }
        
        return node;
    }
    

    }

    public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    public void insert(String word) {
        root.insert(word); 
    }
    
    
    // Returns if the word is in the trie.
    public boolean search(String word) {
        return root.search(word);
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        return root.startsWith(prefix);
    }
    

    }


Log in to reply
 

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