Regular Expression Matching

Decide whether a pattern with dots and stars matches a whole string, by building the answer from smaller ones.

Return true if the pattern p matches the whole of the string s, and false otherwise. A letter in the pattern matches that same letter, and two characters have a special meaning:

Example 1
Input: s = "aa", p = "a"
Output: false
Explanation: "a" matches one a, and the second a is left over.
Example 2
Input: s = "aa", p = "a*"
Output: true
Example 3
Input: s = "aab", p = "c*a*b"
Output: true
Explanation: "c*" matches nothing, "a*" matches "aa" and "b" matches "b".
Solution

The Idea

A pattern is a short way to describe many strings at once. In "c*a*b", the c* stands for any number of c's, none included, the a* for any number of a's, and the last character for one b. So "c*a*b" describes "b", "ab", "aab", "cab", "ccaaab" and many more. The question is whether s is one of them.

Walk through Example 3, where s = "aab". There is no c in it, so c* takes nothing. Then a* takes both a's, and the b takes the b. Every character of the string is used, and so is every part of the pattern, so the answer is true.

The hard part is the star: how many characters should it take? Taking as many as it can does not always work. Try s = "aab" with p = "a*ab". If a* takes both a's, the pattern still needs "ab" but only "b" is left. Here a* has to stop after one a. Each star is a choice, and with several stars the choices multiply.

The way out is to stop choosing a count up front and to look at one character at a time, from the end. Ask whether the first few characters of s match the first few characters of p. If that part of the pattern ends in a letter or a dot, it must match the last character of the string part, and what comes before must match too.

If the pattern part ends in a letter with a star, say a*, there are two cases. Either a* took nothing, so the pattern part without it must match. Or a* took the last character, which must then be an a, and the string part without it must still match the same pattern part, star included.

Each case is a smaller question of the same kind: does a first part of s match a first part of p? There are not many such questions. The string "aab" has 4 first parts, counting the empty one, and "c*a*b" has 6, so there are 24 questions. Look at the picture below, where each of them has its own box.

The match table for s = aab and p = c*a*b. Each row is a first part of s, each column a first part of p, and T means they match. Row "", column c* is T because c* can be used zero times. Row aa, column c*a* is T because a* takes one more a after row a, column c*a*. The answer, row aab, column c*a*b, is T.

Each row is a first part of s, from the empty string "" down to "aab". Each column is a first part of p, and T means the two match. In the teal boxes, row "", column c* is T because c* can take nothing, and an empty string matches an empty pattern: row "", column "".

In the blue boxes, row aa, column c*a*, the last a of "aa" matches the a before the star, so a* takes it. What is left is row a, column c*a*, which is T, so this box is T too. In the orange box, the pattern ends in b and the string ends in b, so the answer copies row aa, column c*a*: T.

So each box is answered from boxes above it or to its left, and each is worked out only once. Saving the answers to these 24 small questions and building the final answer from them is what dynamic programming means here.

Solution Approach

Trying every count for each star works, but the work grows fast. The table avoids that once four things are settled: what an entry means, how it is filled after a letter or a dot, how it is filled after a star, and how the empty-string row starts it.

Trying every count for each star

Why not simply try every count? A method could let the first star take zero characters, then one, then two, and for each of those try every count for the next star. With p = "a*a*a*b" and s = "aaaa", the three stars can share out the four a's in 15 ways. Every way fails at the b, and each is tried in full. Longer strings and more stars make that number grow quickly, while many of the leftover questions repeat.

What one table entry means

The answers go in a two-dimensional boolean array named dp, one entry per box of the picture. Its entry dp[i][j] is true when the first j characters of p match the first i characters of s. With m the length of s and n the length of p, it has m + 1 rows and n + 1 columns, the extra ones for the empty parts. The answer is dp[m][n], the orange box in the picture.

A letter or a dot at the end

What decides dp[i][j] when the pattern part ends in a letter or a dot? Java counts characters from 0, so that last pattern character is p.charAt(j - 1), and the last string character is s.charAt(i - 1). They must match, either as the same letter or because the pattern has a dot. Then the parts before them must match as well, which is dp[i - 1][j - 1], the box one up and one to the left.

A star at the end

What if the last pattern character, p.charAt(j - 1), is a star? The star and the character before it are dropped or used together. Dropping them gives dp[i][j - 2], two boxes to the left. Using them once more needs s.charAt(i - 1) to match the character before the star, and then dp[i - 1][j], the box straight above. If either case is true, so is dp[i][j].

The box above covers two, three or more copies, because it was filled the same way. Row aa, column c*a* reads row a, column c*a*, and that box was T because a* had already taken the first a there.

The row for the empty string

Which box can be filled without reading any other? An empty string matches an empty pattern, so dp[0][0] is true. It also matches a pattern part like "c*a*", where every star takes nothing. So in row 0, a column whose last character is a star copies the box two to the left, and every other box stays false. In the picture, that gives T for c* and c*a* in row "". Column 0 stays false below row 0, because a non-empty string never matches an empty pattern.

Java Solution

The method isMatch works in these steps:

  1. First, keep the lengths of s and p in m and n, and create dp with new boolean[m + 1][n + 1]. Java starts every entry of a new boolean array as false. Set dp[0][0] to true.
  2. Fill row 0 with a loop that moves j from 2 to n. When p.charAt(j - 1) is a star, copy dp[0][j - 2].
  3. Fill rows 1 to m with two nested loops. The outer loop walks i from 1 to m, one string character at a time, and the inner loop walks j from 1 to n, one pattern character at a time. Each step stores p.charAt(j - 1) in pc. A small helper, matches(sc, pc), returns true when pc is a dot or the same character as sc.
  4. When pc is a star, read the character it repeats into before. The variable zero holds dp[i][j - 2], the case where the star takes nothing. The variable more holds whether before matches the string character and dp[i - 1][j] is true. The entry becomes zero || more.
  5. Otherwise, the entry is true when pc matches the string character and dp[i - 1][j - 1] is true.
  6. Once both loops finish, dp[m][n] says whether the whole pattern matches the whole string, and the method returns it.

The main method runs the three examples, then "a*ab" where a star must stop early, ".*" with and without a c after it, two empty strings, and one longer string.

Java
public class RegularExpressionMatching {

    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 = 2; j <= n; j++) {
            if (p.charAt(j - 1) == '*') {
                dp[0][j] = dp[0][j - 2];         // "x*" 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 == '*') {
                    char before = p.charAt(j - 2);
                    boolean zero = dp[i][j - 2];                          // drop "x*"
                    boolean more = matches(s.charAt(i - 1), before) && dp[i - 1][j]; // one more x
                    dp[i][j] = zero || more;
                } else {
                    dp[i][j] = matches(s.charAt(i - 1), pc) && dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];
    }

    private static boolean matches(char sc, char pc) {
        return pc == '.' || pc == sc;
    }

    public static void main(String[] args) {
        System.out.println(isMatch("aa", "a"));
        System.out.println(isMatch("aa", "a*"));
        System.out.println(isMatch("aab", "c*a*b"));
        System.out.println(isMatch("aab", "a*ab"));              // a* must stop after one a
        System.out.println(isMatch("ab", ".*"));                 // ".*" matches anything
        System.out.println(isMatch("ab", ".*c"));                // but the c is still needed
        System.out.println(isMatch("", "a*b*"));                 // empty string, every star unused
        System.out.println(isMatch("", "a"));
        System.out.println(isMatch("mississippi", "mis*is*p*."));
    }
}

Running it prints:

Output
false
true
true
true
true
false
true
false
false

The opening false, true, true are Examples 1 to 3. Look at the fourth line: "aab" against "a*ab" gives true. The table never fixes a count for a*, so the case where it takes one a is found.

The fifth and sixth lines show what ".*" does: any number of any characters. It matches "ab" on its own, but ".*c" gives false, because "ab" has no c at the end. The seventh line, true, comes from row 0 alone: the empty string matches "a*b*" with both stars taking nothing.

The last line is false for "mississippi". Its stars only repeat s and p, so the pattern "mis*is*p*." can produce at most three i's, two plain ones and the dot. The string has four.

Complexity

All the work is filling the table, and each entry takes a fixed amount of work.

  • Time: O(m × n), with m and n the lengths of s and p, because each of the (m + 1) × (n + 1) entries is filled once from at most two earlier entries.
  • Space: O(m × n), because the whole dp table is kept. Each row reads only itself and the row above, so an optional improvement keeps just two rows, for O(n) space.

In Wildcard Matching, a star stands on its own and matches any run of characters, which makes its rule simpler.