211 Add and Search Word - Data structure design

1. Question

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.

2. Implementation

(1) Trie + Backtracking

class WordDictionary {
    class TrieNode {
        char val;
        boolean isWord;
        TrieNode[] childNode;

        public TrieNode(char val) {
            this.val = val;
            childNode = new TrieNode[26];
        }
    }

    TrieNode root;

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

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        if (word == null || word.length() == 0) {
            return;
        }

        TrieNode curNode = root;

        for (char c : word.toCharArray()) {
            int index = c - 'a';

            if (curNode.childNode[index] == null) {
                curNode.childNode[index] = new TrieNode(c);
            }
            curNode = curNode.childNode[index];
        }
        curNode.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 searchByDFS(root, 0, word);
    }

    public boolean searchByDFS(TrieNode node, int depth, String word) {
        if (depth == word.length()) {
            return node.isWord;
        }

        char c = word.charAt(depth);

        if (c == '.') {
            for (TrieNode childNode : node.childNode) {
                if (childNode != null && searchByDFS(childNode, depth + 1, word)) {
                    return true;
                }
            }
            return false;
        }
        else {
            int index = c - 'a';
            return node.childNode[index] != null && searchByDFS(node.childNode[index], depth + 1, word);
        }
    }
}

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

3. Time & Space Complexity

时间复杂度: insert: O(w * L), search: O(26^m), w为放在trie的word的个数,L为word的平均长度,m为查询的word的长度

空间复杂度: O(w * L)

Last updated