Trie with recursive search
Time O(L) add; O(26^dots × L) search worst case Space O(total characters)At index i: if i == length return node.isWord. If word[i] is a dot, return true if any child matches the rest; else follow that letter's child.
class WordDictionary {
private static class Node {
Node[] next = new Node[26];
boolean isWord;
}
private final Node root = new Node();
public WordDictionary() {}
public void addWord(String word) {
Node n = root;
for (char c : word.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.isWord = true;
}
public boolean search(String word) {
return match(root, word, 0);
}
private boolean match(Node n, String w, int i) {
if (i == w.length()) return n.isWord;
char c = w.charAt(i);
if (c == '.') {
for (Node child : n.next) if (child != null && match(child, w, i + 1)) return true;
return false;
}
Node child = n.next[c - 'a'];
return child != null && match(child, w, i + 1);
}
}Verdict: Dots are rare in practice.