[LeetCode 211] Add and Search Word - Data structure design (medium)

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.

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.

Solution

  1. trie结构: add:O(L), search:O(nL)
  2. 用trie树来保存所有单词。
  3. Insert: 因为插入的单词不包含通配符.,直接插入。
  4. Search:用DFS查找包含通配符的单词:
    • 当遇到字母a-z时: 直接进入trie树节点对应的儿子;
    • 当遇到通配符.时:枚举当前trie树节点的所有儿子 (26个子节点,每一个都搜一遍);

Time Complexity:
假设单词长度是 n,共有 k个单词:
1. add: 遍历 n 个节点,所以时间复杂度是 O(n)
2. search:最坏情况下会遍历所有节点,所以时间复杂度是 O(kn)

class WordDictionary {
    
    static class TrieNode {
        TrieNode children [];
        boolean isEndOfWord;
        
        public TrieNode () {
            children = new TrieNode [26];
        }
    }
    
    private TrieNode root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode ();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node = root;
        
        for (char ch : word.toCharArray ()) {
            if (node.children[ch - 'a'] == null) {
                node.children [ch - 'a'] = new TrieNode ();
            }
            
            node = node.children [ch - 'a'];
        }
        
        node.isEndOfWord = 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 search (word, 0, root);
    }
    
    public boolean search (String word, int pointer, TrieNode node) {
        if (node == null) {
            return false;
        }
        
        if (pointer == word.length ()) {
            return node.isEndOfWord;
        }
        
        if (word.charAt (pointer) != '.') {
            return search (word, pointer + 1, node.children [word.charAt (pointer) - 'a']);
        } else {
            for (int i = 0; i < 26; i++) {
                if (search (word, pointer + 1, node.children[i])) {
                    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);
 */

你可能感兴趣的:([LeetCode 211] Add and Search Word - Data structure design (medium))