Approach
Depth-first search
For Add and Search Word - Data structure design, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 40 lines of Java from the credited upstream file 211.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode {2 public TrieNode[] children = new TrieNode[26];3 public boolean isWord = false;4}5 6class WordDictionary {7 public void addWord(final String word) {8 TrieNode node = root;9 for (final char c : word.toCharArray()) {10 final int i = c - 'a';11 if (node.children[i] == null)12 node.children[i] = new TrieNode();13 node = node.children[i];14 }15 node.isWord = true;16 }17 18 public boolean search(final String word) {19 return dfs(word, 0, root);20 }21 22 private TrieNode root = new TrieNode();23 24 private boolean dfs(final String word, int s, TrieNode node) {25 if (s == word.length())26 return node.isWord;27 if (word.charAt(s) != '.') {28 TrieNode next = node.children[word.charAt(s) - 'a'];29 return next == null ? false : dfs(word, s + 1, next);30 }31 32 33 for (int i = 0; i < 26; ++i)34 if (node.children[i] != null && dfs(word, s + 1, node.children[i]))35 return true;36 37 return false;38 }39}40