Friday, May 26, 2017

211. 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.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.



Solution:

The idea is to implement a Trie to store the words.

The tricky part is to handle ".".

When we meet a ".", we just try all 26 possible characters and check if from any one we can get find this word.



Code:


public class WordDictionary {
    
    class TrieNode {
        public TrieNode[] link;
        public boolean isEnd;
        public TrieNode() {
            link = new TrieNode[26];
            for (int i = 0; i < 26; i++) {
                link[i] = null;
            }
            this.isEnd = false;
        }
    }

    private TrieNode root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
        
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (curr.link[c - 'a'] == null) {
                curr.link[c - 'a'] = new TrieNode();
            }
            curr = curr.link[c - 'a'];
        }
        curr.isEnd = 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 find(word, root, 0);
    }
    
    public boolean find(String word, TrieNode root, int index) {
        if (index == word.length()) {
            return root.isEnd;
        }
        char c = word.charAt(index);
        if (c == '.') {
            for (int i = 0; i < 26; i++) {
                if (root.link[i] != null) {
                    if (find(word, root.link[i], index + 1)) {
                        return true;
                    }
                }
            }
            return false;
        }
        else if (root.link[c - 'a'] != null){
            return find(word, root.link[c - 'a'], index + 1);
        }
        else {
            return false;
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */