Approach
Depth-first search
For Word Pattern II, 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
- 46 lines of Java from the credited upstream file 291.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 1 loop block 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 Solution {2 public boolean wordPatternMatch(String pattern, String s) {3 return isMatch(pattern, 0, s, 0, new HashMap<>(), new HashSet<>());4 }5 6 private boolean isMatch(final String pattern, int i, final String s, int j,7 Map<Character, String> charToString, Set<String> seen) {8 if (i == pattern.length() && j == s.length())9 return true;10 if (i == pattern.length() || j == s.length())11 return false;12 13 final char c = pattern.charAt(i);14 15 if (charToString.containsKey(c)) {16 final String t = charToString.get(c);17 18 if (!s.startsWith(t, j))19 return false;20 21 22 return isMatch(pattern, i + 1, s, j + t.length(), charToString, seen);23 }24 25 for (int k = j; k < s.length(); ++k) {26 final String t = s.substring(j, k + 1);27 28 29 if (seen.contains(t))30 continue;31 32 charToString.put(c, t);33 seen.add(t);34 35 if (isMatch(pattern, i + 1, s, k + 1, charToString, seen))36 return true;37 38 39 charToString.remove(c);40 seen.remove(t);41 }42 43 return false;44 }45}46