My Simple and clean Java Code without need of storing character at each node


  • 0
    S

    '''
    class WordDictionary {

    class TrieNode{
        public TrieNode[] arr;
        public boolean isWord;
        public TrieNode(){
            arr = new TrieNode[26];
            isWord = false;
        }
    }
    
    private TrieNode root;
    
    public WordDictionary() {
        root = new TrieNode();
    }
    
    public void addWord(String word) {
        TrieNode current = root;
        for(int i=0; i<word.length();i++){
            int pos = word.charAt(i) - 'a';
            if(current.arr[pos] == null){
                current.arr[pos] = new TrieNode();
            }
            current = current.arr[pos];
        }
        current.isWord = true;
    }
    
    public boolean search(String word) {
        TrieNode current = root;
        return helper(root,word,0);
    }
    
    private boolean helper(TrieNode current,String word, int i){
        
        if(i==word.length())  return current.isWord;
        
        if(word.charAt(i) == '.'){
            boolean result = false;
            for(int j=0; j<26;j++){
                if(current.arr[j] != null){
                    if(helper(current.arr[j],word,i+1))
                        return true;
                }
            }
        }
        else return current.arr[word.charAt(i)-'a'] != null && helper(current.arr[word.charAt(i)-'a'],word,i+1);
        
        return false;
    }
    

    }
    '''


Log in to reply
 

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