Add and Search Word

Design a data structure that supports the following two operations: addWord(word) and 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.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad")  // return false
search("bad")  // return true
search(".ad")  // return true
search("b..")  // return true

Solution:

We can create a trie to store all the data. During search, when we meet a dot, we will check all possible candidates on that level of the trie.

Code:

public class WordDictionary {

    class TrieNode {
        TrieNode[] next;
        boolean isWord;
        public TrieNode() {
            next = new TrieNode[26];
            isWord = false;
        }
    }

    TrieNode root = new TrieNode();

    public void addWord(String word) {
        if (word == null || word.length() == 0) {
            return;
        }
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            int c = word.charAt(i) - 'a';
            if (p.next[c] == null) {
                p.next[c] = new TrieNode();
            }
            p = p.next[c];
        }
        p.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) {
        if (word == null || word.length() == 0) {
            return false;
        }
        return find(word, 0, root);
    }

    private boolean find(String word, int i, TrieNode p) {
        if (i == word.length()) {
            return p.isWord;
        }
        char c = word.charAt(i);
        if (c == '.') {
            for (int j = 0; j < p.next.length; j++) {
                if (p.next[j] != null && find(word, i + 1, p.next[j])) {
                    return true;
                }
            }
        } else if (p.next[c - 'a'] != null) {
            return find(word, i + 1, p.next[c - 'a']);
        }
        return false;
    }
}

results matching ""

    No results matching ""