44. Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.

  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Example 4:

Example 5:

DP的方法要先建立一個size為(m + 1) * (n + 1)的2D dp table,dp[i][j]代表s[0...i - 1]和p[0...j-1]是否match。 dp[0][j] = dp[0][j - 1] if j > 1 and p[j - 1] == '*' 1. dp[i][j] = dp[i - 1][j - 1] if s[i - 1] == p[j - 1] || p[j - 1] == '?' 2. dp[i][j] = dp[i - 1][j] || dp[i][j - 1] if p[j - 1] == '*' dp[i - 1][j]的情形是s[0...i - 2]和p[0...j - 1]match然後p[j - 1]這個'*'要match更多的characters。 dp[i][j - 1]的情形是s[0...i - 1]和p[0...j - 2]match然後p[j - 1]這個'*'要match empty sequence。

Last updated

Was this helpful?