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
- 42 lines of Python from the credited upstream file 291.py.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit 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 Solution:2 def wordPatternMatch(self, pattern: str, s: str) -> bool:3 def isMatch(4 i: int, j: int, charToString: dict[str, str],5 seen: set[str]) -> bool:6 if i == len(pattern) and j == len(s):7 return True8 if i == len(pattern) or j == len(s):9 return False10 11 c = pattern[i]12 13 if c in charToString:14 t = charToString[c]15 16 if t not in s[j:]:17 return False18 19 20 return isMatch(i + 1, j + len(t), charToString, seen)21 22 for k in range(j, len(s)):23 t = s[j:k + 1]24 25 26 if t in seen:27 continue28 29 charToString[c] = t30 seen.add(t)31 32 if isMatch(i + 1, k + 1, charToString, seen):33 return True34 35 36 del charToString[c]37 seen.remove(t)38 39 return False40 41 return isMatch(0, 0, {}, set())42