211. Add and Search Word - Data structure design

Description

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.

click to show hint.

You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.

Solution

DFS

再次注意Trie不需要char val作为成员变量!另外在dfsSearch的外层已经检查了node != null,所以可以默认node != null,无需加多余的检查。

复杂度分析:

  • addWord: time O(wordLen)
  • search: average time O(min(height, wordLen)), worst time O(26 ^ n)
class WordDictionary {
    private Trie root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new Trie();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        Trie node = root;
        
        for (char c : word.toCharArray()) {
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a'] = new Trie();
            }
            node = node.children[c - 'a'];
        }
        
        node.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) {
        return dfsSearch(word, 0, root);
    }
    
    private boolean dfsSearch(String word, int start, Trie node) {
        if (start == word.length()) {   // node is non-null
            return node.isWord;
        }
        
        char c = word.charAt(start);
        
        if (c == '.') {
            for (Trie child : node.children) {  // make sure child is non-null
                if (child != null && dfsSearch(word, start + 1, child)) {
                    return true;
                }
            }
        } else if (node.children[c - 'a'] != null) {
            return dfsSearch(word, start + 1, node.children[c - 'a']);
        }
        
        return false;
    }
    
    class Trie {
        Trie[] children;
        boolean isWord;
        
        public Trie() {
            children = new Trie[26];
        }
    }
}

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

你可能感兴趣的:(211. Add and Search Word - Data structure design)