Wildcard Matching

Check whether a pattern with ? and * matches a whole string, using a table of matches between shorter parts.

Given a string s and a pattern p, return true if the pattern matches the whole string, and false otherwise. A letter in the pattern matches that same letter. Two characters are wildcards, which means they stand in for other characters:

Example 1
Input: s = "aa", p = "a"
Output: false
Explanation: the pattern has room for one character, but the string has two.
Example 2
Input: s = "aa", p = "*"
Output: true
Explanation: the star takes both characters.
Example 3
Input: s = "adceb", p = "*a*b"
Output: true
Explanation: the first '*' matches nothing, the second matches "dce".
Solution

The Idea

You have probably typed a pattern like *.txt to find files: the star stands for any name, and only names ending in .txt are kept. This problem asks the same of one string. Does s fit the pattern p, from its first character to its last?

Take Example 3, where s = "adceb" and p = "*a*b". The pattern wants an a somewhere, and a b as the very last character. The first star takes nothing, the a takes the a, the second star takes "dce", and the b takes the b. Every character of the string is used, so the answer is true.

The hard part is deciding how much each star should take. Taking as little as possible fails for s = "abcb" and p = "a*b". If the star takes nothing, the pattern's b matches the first b, and "cb" is left over. The star has to take "bc" instead. Taking as much as possible fails too: with s = "ab" and p = "*b", a star that takes both letters leaves nothing for the b. With several stars, each one has its own choice, and the choices multiply.

The way out is to stop picking amounts up front and to ask smaller questions instead. Do the first few characters of s match the first few characters of p? If that pattern part ends in a letter or a '?', it must match the last character of the string part, and everything before those two characters must match as well.

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" has 5, so there are 30 such questions. Look at the picture below, where each question has its own box.

The match table for s = adceb and p = *a*b. Each row is a first part of s, each column a first part of p, and T means they match. Row "" is T under "" and *. Row adc, column *a* is T because the star takes the c and the box above is T. The answer, row adceb, column *a*b, is T because b matches b and the box up and to the left is T.

Each row is a first part of s, from "" down to "adceb", and each column is a first part of p. A T means the two match. In the teal boxes of row "", the empty string matches the empty pattern, and it matches "*" too, because the star takes nothing.

In the blue boxes, row adc, column *a* asks whether "adc" matches "*a*". The star can take the c, which leaves row ad, column *a*, the box above. That box is T, so this one is T too. In the orange boxes, "adceb" and "*a*b" both end in b, so the answer copies row adce, column *a*, which is T.

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 '?', how it is filled after a star, and how row "" starts it.

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", such a method makes 1,772 calls before it answers false. The table for the same input has 21 rows and 7 columns, so only 147 different questions exist, and most of those calls repeat one already answered.

What one table entry means

The table is a boolean array named dp. The entry dp[i][j] is true when the first i characters of s match the first j characters of p. With m the length of s and n the length of p, it has m + 1 rows and n + 1 columns. The extra row and column hold the empty parts, and the answer is dp[m][n], the orange box in row adceb.

A letter or a question mark at the end

What decides dp[i][j] when the pattern part does not end in a star? Positions in a Java string start at 0, so the last pattern character is p.charAt(j - 1) and the last string character is s.charAt(i - 1). A '?' accepts any character there, and a letter accepts only itself. If they fit, the entry copies dp[i - 1][j - 1], the box up and to the left, which covers everything before those two characters. If they do not fit, the entry stays false.

A star at the end

What if p.charAt(j - 1) is a star? Taking nothing gives dp[i][j - 1], the box to the left, whose pattern part ends just before the star. Taking the last string character gives dp[i - 1][j], the box above, where the same star still ends the pattern part. A star accepts any character, so no comparison is needed, and dp[i][j] is true if either box is true.

Look at column *a* in the picture. Row a is T from the box to its left, where the star takes nothing. Every box below it copies the box above, so the star takes the d, then the c, then the e, then the b.

The row for the empty string

Where does the table start? Two empty parts match, so dp[0][0] is true. The empty string also matches a pattern part made only of stars, such as "**", because each star takes nothing. Once the pattern part has any other character, the empty string cannot match it, so the rest of row 0 stays false. In the picture, row "" is T under "" and *, and empty from *a on. Column 0 stays false below row 0, because a pattern with no characters cannot match a string that has some.

Java Solution

The method isMatch works in these steps:

  1. First, store the lengths of s and p in m and n, and create the table dp as new boolean[m + 1][n + 1], whose entries all start as false. Set dp[0][0] to true.
  2. Fill row 0 with a loop that moves j forward from 1 while p.charAt(j - 1) is a star, setting dp[0][j] to true. The loop stops at the first pattern character that is not a star.
  3. Fill the other rows with two loops, one inside the other. The outer loop moves i from 1 to m over the string, and the inner loop moves j from 1 to n over the pattern. Each step reads the pattern character into pc.
  4. When pc is a star, the entry becomes dp[i][j - 1] || dp[i - 1][j]: the star takes nothing, or it takes one more character.
  5. Otherwise, the entry is true when pc is '?' or equals s.charAt(i - 1), and dp[i - 1][j - 1] is true.
  6. After both loops, return dp[m][n], the entry for the whole string and the whole pattern.

A small helper, show, prints one call and its result. The main method uses it on the three examples, on "abcb" with "a*b", "acdcb" with "a*c?b" and "cb" with "?a", and on the empty string against "", "***" and "*a".

Java
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:

Output
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" matches "a*b" because the table lets the star take "bc", where taking as little as possible failed. The fifth line is false. After "a*", the pattern needs a c, any one character and a b at the end, but "acdcb" ends in "dcb", which starts with d.

On the sixth line, the '?' in "?a" takes the c, but the pattern's a meets the string's b, so the answer is false. The last three lines check row 0. Two empty parts match, and "***" matches the empty string because every star takes nothing, while the a in "*a" needs a character the empty string does not have.

The loop for row 0 is easy to leave out, and it matters. Without it, column * in the picture never gets its first T, so every box under it stays empty. Run that way, Example 3 returns false instead of true.

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 dp 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).

In Regular Expression Matching, a star repeats only the character before it, and a table of the same shape solves it.