211. Design Add and Search Words Data Structure

Link

Solution

class Node{
    
    public Node[] children = new Node[26];
    public char c;
    public boolean isWord;
    
    public Node(char c){
        this.c = c;
    }
    
}


class WordDictionary {

    Node root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new Node(' ');
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        Node it = root;
        for(char c : word.toCharArray()){
            if(it.children[c-'a'] == null){
                it.children[c-'a'] = new Node(c);
            }
            it = it.children[c-'a'];
        }
        it.isWord = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
       return match(word.toCharArray(), 0, root);
    }
    
    public boolean match(char[] word, int index, Node node){
        if(node == null) return false;
        if(index >= word.length) return node.isWord;
        char c = word[index++];
        if(c != '.'){
            return match(word, index, node.children[c-'a']);
        }
        else{
            for(int i = 0; i < 26; i++){
                if(match(word, index, node.children[i])) return true;
            }
            return false;
        }
    }
    
}

Last updated

Was this helpful?