Overview
This is a classic 2D DP problem. The `?` matches any single character. The `*` is the tricky part—it matches ANY sequence of characters (including the empty sequence).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
This is a classic 2D DP problem. The `?` matches any single character. The `*` is the tricky part—it matches ANY sequence of characters (including the empty sequence).
`dp[i][j]` is `true` if the first `i` characters of `s` match the first `j` characters of `p`. We pad the strings with a 1-indexed approach to handle empty string base cases elegantly.
If the characters match exactly, or if the pattern character is `?`, then `dp[i][j]` simply takes the value from diagonally above-left: `dp[i-1][j-1]`.
If the pattern is `*`, it can either act as empty (`dp[i][j-1]`), or it can swallow the current character of `s` and remain active for the next (`dp[i-1][j]`).
| "" | '*' | 'a' | |
|---|---|---|---|
| "" | F | F | F |
| 'b' | F | F | F |
| 'a' | F | F | F |
| 'a' | F | F | F |