The Wildcard Pattern Matching problem involves finding if a given string matches a pattern that contains special characters called wildcards. Wildcards can match any character in the string. There are two types of wildcards, ‘*‘ and ‘?‘. The ‘*‘ wildcard matches zero or more characters, while the ‘?‘ wildcard matches any single character.
For example, the pattern ‘h*llo?‘ matches the strings "hello", "hallo", "hxllo1", and "hcllo?", but not "hllo" or "hellno".
To solve this problem using dynamic programming, we can define a 2D boolean array ‘dp‘, where ‘dp[i][j]‘ represents if the prefix of the string up to index ‘i‘ matches the pattern up to index ‘j‘.
We can start by initializing ‘dp[0][0]‘ to ‘true‘, since an empty string matches an empty pattern. We can then fill in the first row of ‘dp‘ to check if the pattern matches an empty string.
Next, we can iterate through the remaining cells in ‘dp‘, using the following recurrence relation:
if (pattern.charAt(j - 1) == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
} else if (pattern.charAt(j - 1) == '?' || pattern.charAt(j - 1) == str.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = false;
}
The first case handles the ‘*‘ wildcard. If the current character in the pattern is ‘*‘, we can either choose to ignore it (i.e. match zero characters), or match the current character in the string by setting ‘dp[i][j]‘ to ‘dp[i][j-1]‘ (ignore the wildcard) or ‘dp[i-1][j]‘ (match the wildcard by adding a character to the string).
The second case handles the ‘?‘ wildcard or a matching character. If the current character in the pattern is a ‘?‘ or matches the current character in the string, we simply continue to match the remaining characters by setting ‘dp[i][j]‘ to ‘dp[i-1][j-1]‘.
The third case covers any other scenario where the pattern and string do not match. In this case, we set ‘dp[i][j]‘ to ‘false‘.
At the end of the iteration, ‘dp[str.length()][pattern.length()]‘ will tell us if the entire string matches the entire pattern.
Here is the code implementation in Java:
public static boolean isWildcardMatch(String str, String pattern) {
boolean[][] dp = new boolean[str.length() + 1][pattern.length() + 1];
dp[0][0] = true;
// Fill first row
for (int j = 1; j <= pattern.length(); j++) {
if (pattern.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
}
}
// Fill remaining cells
for (int i = 1; i <= str.length(); i++) {
for (int j = 1; j <= pattern.length(); j++) {
if (pattern.charAt(j - 1) == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
} else if (pattern.charAt(j - 1) == '?' || pattern.charAt(j - 1) == str.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = false;
}
}
}
return dp[str.length()][pattern.length()];
}