Easy understand Java Code


  • 0
    N
    class TrieNode {
    // Initialize your data structure here.
    private char value;
    private int count = 0;
    private TrieNode[] childs = new TrieNode[26];
    public TrieNode() {
        
    }
    public TrieNode(char value){
        this.value = value;
    }
    
    public TrieNode getNode(char c){
    	return childs[c-97];
    }
    public TrieNode insertNode(char c){
    	TrieNode node = new TrieNode(c);
    	childs[c-97]=node;
    	return node;
    }
    public void increaseCount(){
    	this.count++;
    }
    public int getCount(){
    	return count;
    }
    

    }

    public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    public void insert(String word) {
        char[] charArr = word.toCharArray();
        TrieNode current = root;
        for(char c:charArr){
        	TrieNode next = current.getNode(c);
        	if(next == null){
        		next = current.insertNode(c);
        	}
        	current =  next;
        }
        current.increaseCount();
    }
    
    // Returns if the word is in the trie.
    public boolean search(String word) {
    	TrieNode lastNode = getLastNode(word);
    	if(lastNode == null){
    		return false;
    	}
    	return lastNode.getCount()>0;
    }
    
    private TrieNode getLastNode(String key){
    	char[] charArr = key.toCharArray();
    	TrieNode current = root;
    	for(char c:charArr){
    		TrieNode next = current.getNode(c);
    		if(next == null){
    			return null;
    		}
    		current = next;
    	}
    	return current;
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
    	return getLastNode(prefix)!=null;
    }
    

    }


Log in to reply
 

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