Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 44 Wildcard Matching - Walkthrough

Pattern matching DP

Match pattern pp with wildcards against string ss. '?' matches any char, '*' matches any sequence. dp[i][j]dp[i][j] = true if p[0..i1]p[0..i-1] matches s[0..j1]s[0..j-1].

Handle '' carefully: it can match empty or extend. For '': dp[i][j]=dp[i1][j]dp[i][j] = dp[i-1][j] (match empty) OR dp[i][j1]dp[i][j-1] (extend match). For '?': dp[i][j]=dp[i1][j1]dp[i][j] = dp[i-1][j-1]. Example: pattern "a*b" matches "axxxb", "ab", "axyzzb". Time: O(mn)O(mn), Space: O(mn)O(mn) or O(n)O(n) with improvement.