Wildcard Matching
Check whether a pattern with ? and * matches a whole string, using a table of matches between shorter parts.
Given a string sptruefalse
matches any single character.'?' matches any sequence of characters, including the empty sequence.'*'
Example 1
Output: false
Explanation: the pattern has room for one character, but the string has two.
Example 2
Output: true
Explanation: the star takes both characters.
Example 3
Output: true
Explanation: the first '*' matches nothing, the second matches "dce".
The Idea
You have probably typed a pattern like *.txtsp
Take Example 3, where s = "adceb"p = "*a*b"
The hard part is deciding how much each star should take. Taking as little as possible fails for s = "abcb"p = "a*b"s = "ab"p = "*b"
The way out is to stop picking amounts up front and to ask smaller questions instead. Do the first few characters of sp'?'
If the pattern part ends in a star, there are two cases. The star may take nothing, so the string part must match the pattern part without that star. Or the star takes the last character of the string part, and the shorter string part must still match the same pattern part, star included. That second case can repeat, so the star takes two, three or more characters, one at a time.
Each case leads to a smaller question of the same kind. The string "adceb" has 6 first parts, counting the empty one, and "*a*b"
Each row is a first part of sp"*"
In the blue boxes, row adc, column *a*"*a*"*a*"*a*b"*a*
So each box needs only boxes above it or to its left, and each is worked out once. Saving the answers to these 30 small questions and building the final answer from them is called dynamic programming.
Solution Approach
Trying every length for each star gives the right answer but repeats a lot of work. The table avoids that once four things are settled: what an entry means, how it is filled after a letter or a '?'
Trying every length for each star
Why not let each star try every length in turn? A method can give the first star zero characters, then one, then two, and for each choice try every length for the next star. For a string of 20 a's and the pattern "*a*a*b"
What one table entry means
The table is a booleandpdp[i][j]isjpmsnpm + 1n + 1dp[m][n]
A letter or a question mark at the end
What decides dp[i][j]p.charAt(j - 1)s.charAt(i - 1)'?'dp[i - 1][j - 1]
A star at the end
What if p.charAt(j - 1)dp[i][j - 1]dp[i - 1][j]dp[i][j]
Look at column *a*
The row for the empty string
Where does the table start? Two empty parts match, so dp[0][0]"**"**a
Java Solution
The method isMatch
- First, store the lengths of
ands inp andm , and create the tablen asdp , whose entries all start as false. Setnew boolean[m + 1][n + 1] to true.dp[0][0] - Fill row 0 with a loop that moves
forward from 1 whilej is a star, settingp.charAt(j - 1) to true. The loop stops at the first pattern character that is not a star.dp[0][j] - Fill the other rows with two loops, one inside the other. The outer loop moves
from 1 toi over the string, and the inner loop movesm from 1 toj over the pattern. Each step reads the pattern character inton .pc - When
is a star, the entry becomespc : the star takes nothing, or it takes one more character.dp[i][j - 1] || dp[i - 1][j] - Otherwise, the entry is true when
ispc or equals'?' , ands.charAt(i - 1) is true.dp[i - 1][j - 1] - After both loops, return
, the entry for the whole string and the whole pattern.dp[m][n]
A small helper, showmain"abcb""a*b""acdcb""a*c?b""cb""?a""""***""*a"
public class WildcardMatching {
public static boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
// dp[i][j]: the first i characters of s match the first j characters of p
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true; // empty string, empty pattern
for (int j = 1; j <= n && p.charAt(j - 1) == '*'; j++) {
dp[0][j] = true; // leading stars can match nothing
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') {
dp[i][j] = dp[i][j - 1] // the star takes nothing
|| dp[i - 1][j]; // the star takes one more character
} else {
dp[i][j] = (pc == '?' || pc == s.charAt(i - 1)) && dp[i - 1][j - 1];
}
}
}
return dp[m][n];
}
static void show(String s, String p) {
System.out.println("isMatch(\"" + s + "\", \"" + p + "\") = " + isMatch(s, p));
}
public static void main(String[] args) {
show("aa", "a");
show("aa", "*");
show("adceb", "*a*b");
show("abcb", "a*b");
show("acdcb", "a*c?b");
show("cb", "?a");
show("", "");
show("", "***");
show("", "*a");
}
}
Running it prints:
isMatch("aa", "a") = false
isMatch("aa", "*") = true
isMatch("adceb", "*a*b") = true
isMatch("abcb", "a*b") = true
isMatch("acdcb", "a*c?b") = false
isMatch("cb", "?a") = false
isMatch("", "") = true
isMatch("", "***") = true
isMatch("", "*a") = false
Look at the fourth line: "abcb""a*b""a*""acdcb"
On the sixth line, the '?'"?a""***""*a"
The loop for row 0 is easy to leave out, and it matters. Without it, column *
Complexity
All the work is in filling the table, and each box costs the same small amount.
- Time: O(m × n), because the two loops visit each of the m × n boxes outside row 0 and column 0 once, and each box reads at most two other boxes.
- Space: O(m × n), because
keeps all (m + 1) × (n + 1) answers. Each row reads only itself and the row above, so keeping two rows of n + 1 values would bring this down to O(n).dp
In