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 lettersa-zor.. 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 lettersa-z.

tag: Trie

class WordDictionary {

    private class TrieNode{
        TrieNode[] children;
        boolean isWord;

        public TrieNode(){
            children = new TrieNode[26];
            isWord = false;
        }

        public void insert(String word, int index){
            if (index == word.length()){
                isWord = true;
                return;
            }

            int pos = word.charAt(index) - 'a';

            if (children[pos] == null){
                children[pos] = new TrieNode();
            }

            children[pos].insert(word, index + 1);
        }

        public boolean search(String word, int index){
            if (index == word.length()){
                return this.isWord;
            }

            if (word.charAt(index) == '.'){
                for (int i = 0; i < 26; i++){
                    if (children[i] != null && children[i].search(word, index + 1)) return true;
                }

                return false;
            }
            else{
                int pos = word.charAt(index) - 'a';

                if (children[pos] == null) return false;

                return children[pos].search(word, index + 1);
            }
        }
    }

    TrieNode root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        root.insert(word, 0);
    }

    /** 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 root.search(word, 0);
    }
}

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

results for ""

    No results matching ""