. and *.
Problem
Given an input strings and a pattern p, implement regular expression matching with support for . and *.
The character
. matches any single character.
The character
* matches zero or more occurrences of the character immediately before it.
The entire string must match the pattern.
Example 1
Input
s = "aa"
p = "a"
Output
false
Example 2
Input
s = "aa"
p = "a*"
Output
true
Example 3
Input
s = "ab"
p = ".*"
Output
true
Solution
This problem can be solved using Dynamic Programming with Memoization. We compare the characters ofs and p using two indexes: i for the string and j for the pattern.
At each state
(i, j), we first check whether the current characters match. Two characters match when they are equal or the pattern character is ..
If the next pattern character is
*, we have two choices. We can treat * as matching zero occurrences and move the pattern forward by two positions. Or, if the current characters match, we can let * consume the current character and move only the string index forward.
For example, with
s = "aaa" and p = "a*", the * can match one, two, or all three occurrences of a.
If the next pattern character is not
*, the current characters must match and both indexes move forward.
When the string is fully consumed, the pattern must also be fully consumed. However, remaining pattern characters can still match an empty string if they occur in
x* pairs.
The result for each
(i, j) state is stored in the memo array to avoid recalculating the same subproblem.
class Solution {
public boolean isMatch(String s, String p) {
Boolean[][] memo = new Boolean[s.length() + 1][p.length() + 1];
return isMatch(s, p, 0, 0, memo);
}
private boolean isMatch(
String s, String p, int i, int j, Boolean[][] memo) {
if (j == p.length())
return i == s.length();
if (memo[i][j] != null)
return memo[i][j];
boolean match = i < s.length() &&
(s.charAt(i) == p.charAt(j) || p.charAt(j) == '.');
if (j + 1 < p.length() && p.charAt(j + 1) == '*') {
return memo[i][j] =
isMatch(s, p, i, j + 2, memo) ||
(match && isMatch(s, p, i + 1, j, memo));
}
return memo[i][j] =
match && isMatch(s, p, i + 1, j + 1, memo);
}
}
Complexity
There are(m + 1) × (n + 1) possible states, where m is the length of s and n is the length of p. Each state is calculated only once, so the time complexity is O(m × n).
The memoization array stores
O(m × n) states, and the recursion stack can grow up to O(m + n). Therefore, the extra space complexity is O(m × n).
Comments
No comments yet. Ask a question or share what helped.