Friday, April 14, 2017

211. Add and Search Word - Data structure design

Trie + Recursion
 89.06%
public class WordDictionary {
    private TrieNode root;
    private class TrieNode {
        public boolean isWord;
        public TrieNode[] children;
        public TrieNode() {
            children = new TrieNode[26];
        }
    }

    public WordDictionary() {
        root = new TrieNode();
    }

    // Adds a word into the data structure.
    public void addWord(String word) {
        // Write your code here
        TrieNode curr = root;
        int index;
        for (int i = 0; i < word.length(); i++) {
            index = word.charAt(i) - 'a';
            if (curr.children[index] == null) curr.children[index] = new TrieNode();
            curr = curr.children[index];
        }
        curr.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) {
        // Write your code here
        return search(word, 0, root);
    }
    private boolean search(String word, int start, TrieNode curr) {
        if (start == word.length()) return curr.isWord;
        int index = word.charAt(start) - 'a';
        if (index != '.' - 'a') {
            if (curr.children[index] == null) return false;
            return search(word, start + 1, curr.children[index]);
        } else {
            //iterate from 'a' to 'z'
            for (char c = 0; c <= 'z' - 'a'; c++) {
                if (curr.children[c] == null)  continue;
                if (search(word, start + 1, curr.children[c])) return true;
            }
            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);
 */

No comments:

Post a Comment