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()];
}