Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
where:
'?'
Matches any single character.'*'
Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
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:Input: s = “cb”, p = “?a” Output: false Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.
Java Solution
You can implement wildcard pattern matching using dynamic programming. Here’s a Java solution for the given problem:
public class WildcardMatching {
public static boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
} else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
System.out.println(isMatch("aa", "a")); // Output: false
System.out.println(isMatch("aa", "*")); // Output: true
System.out.println(isMatch("cb", "?a")); // Output: false
}
}
This solution uses a 2D array dp
to store the intermediate results. The entry dp[i][j]
represents whether the first i
characters of string s
match the first j
characters of pattern p
. The dynamic programming approach efficiently computes the solution in O(m * n) time complexity, where m and n are the lengths of the input strings s
and p
, respectively.
Python Solution
def isMatch(s, p):
m, n = len(s), len(p)
# Initialize a 2D array for dynamic programming
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
# Handle patterns with '*' at the beginning
for j in range(1, n + 1):
if p[j - 1] == '*':
dp[0][j] = dp[0][j - 1]
# Dynamic programming to fill the rest of the array
for i in range(1, m + 1):
for j in range(1, n + 1):
if p[j - 1] == '*':
dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
elif p[j - 1] == '?' or s[i - 1] == p[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
return dp[m][n]
# Test cases
print(isMatch("aa", "a")) # Output: False
print(isMatch("aa", "*")) # Output: True
print(isMatch("cb", "?a")) # Output: False
This Python code follows the same dynamic programming approach as the Java solution. It uses a 2D array dp
to store intermediate results and determines whether the entire input string s
matches the pattern p
.