← Back to index
HardPHP4 min read

Wildcard Matching

match string against pattern with ? and * using dynamic programming.

dynamic-programmingstringgreedy

Problem link

View on LeetCode

Solutions in this repo

  • PHP../wildcard-matching/solution.phpPHP solution

dp[i][j] = true if s[0..i] matches p[0..j]. ? matches any single character. * matches any sequence including empty.

for *, try matching zero characters (skip *) or one or more characters (consume string). can optimize space to O(n) by using only previous row.

cases

  • exact match: s[i] == p[j]
  • ?: p[j] == '?' matches any character
  • *: matches zero or more characters

complexity

O(mn) time where m and n are string and pattern lengths. O(mn) space, can be optimized to O(n).