Regular Expression Matching
Decide whether a pattern with dots and stars matches a whole string, by building the answer from smaller ones.
Return truepsfalse
matches any single character.'.' matches zero or more copies of the character just before it. Every'*' in the pattern comes right after a letter or a'*' .'.'
Example 1
Output: false
Explanation: "a" matches one a, and the second a is left over.
Example 2
Output: true
Example 3
Output: true
Explanation: "c*" matches nothing, "a*" matches "aa" and "b" matches "b".
The Idea
A pattern is a short way to describe many strings at once. In "c*a*b"c*a*"c*a*b"s
Walk through Example 3, where s = "aab"c*a*
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"p = "a*ab"a*a*
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 sp
If the pattern part ends in a letter with a star, say a*a*a*
Each case is a smaller question of the same kind: does a first part of sp"c*a*b"
Each row is a first part of spc*c*
In the blue boxes, row aa, column c*a*a*c*a*c*a*
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"s = "aaaa"
What one table entry means
The answers go in a two-dimensional booleandpdp[i][j]jpismsnpm + 1n + 1dp[m][n]
A letter or a dot 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 the last pattern character, p.charAt(j - 1)dp[i][j - 2]s.charAt(i - 1)dp[i - 1][j]dp[i][j]
The box above covers two, three or more copies, because it was filled the same way. Row aa, column c*a*c*a*a*
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]"c*a*"c*c*a*
Java Solution
The method isMatch
- First, keep the lengths of
ands inp andm , and createn withdp . Java starts every entry of a newnew boolean[m + 1][n + 1] array as false. Setboolean to true.dp[0][0] - Fill row 0 with a loop that moves
from 2 toj . Whenn is a star, copyp.charAt(j - 1) .dp[0][j - 2] - Fill rows 1 to
with two nested loops. The outer loop walksm from 1 toi , one string character at a time, and the inner loop walksm from 1 toj , one pattern character at a time. Each step storesn inp.charAt(j - 1) . A small helper,pc , returns true whenmatches(sc, pc) is a dot or the same character aspc .sc - When
is a star, read the character it repeats intopc . The variablebefore holdszero , the case where the star takes nothing. The variabledp[i][j - 2] holds whethermore matches the string character andbefore is true. The entry becomesdp[i - 1][j] .zero || more - Otherwise, the entry is true when
matches the string character andpc is true.dp[i - 1][j - 1] - Once both loops finish,
says whether the whole pattern matches the whole string, and the method returns it.dp[m][n]
The main"a*ab"".*"
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:
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""a*ab"a*
The fifth and sixth lines show what ".*"".*c""a*b*"
The last line is false for "mississippi""mis*is*p*."
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
ands , because each of the (m + 1) × (n + 1) entries is filled once from at most two earlier entries.p - Space: O(m × n), because the whole
table is kept. Each row reads only itself and the row above, so an optional improvement keeps just two rows, for O(n) space.dp
In