Add and Search Word Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note: You may assume that all words are consist of lowercase letters a-z.

click to show hint. You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.

Solution:

public class WordDictionary {

    class Node {
        boolean isLeaf;
        Node[] next = new Node[26];
    }
    
    Node root = new Node();
    
    // Adds a word into the data structure.
    public void addWord(String word) {
        Node cur = root;
        for(int i=0; i<word.length(); i++){
            char ch = word.charAt(i);
            if(cur.next[ch-'a']==null){
                cur.next[ch-'a'] = new Node();
            }
            cur = cur.next[ch-'a'];
        }
        cur.isLeaf = 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 search(word, root);
    }
    
    public boolean search(String word, Node node){
        if(word.length()==0) return node.isLeaf;
        char ch = word.charAt(0);
        if(ch=='.'){
            for(Node n : node.next){
                if(n!=null){
                    if(search(word.substring(1), n)){
                        return true;
                    }
                }
            }
        } else {
            if(node.next[ch-'a']==null){
                return false;
            }
            return search(word.substring(1), node.next[ch-'a']);
        }
        return false;
    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
comments powered by Disqus