Description
Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a") → true
isMatch("aa", ".") → true
isMatch("ab", ".") → true
isMatch("aab", "ca*b") → true
Solution
DP, time O(m * n), space O(m * n)
以前用DFS就可以AC,但是现在会TLE,必须祭出DP大法啦。
注意必须预处理j = 0的情况!考虑s = "", p = "a*",如果没有预处理,则结果会返回F。
- If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];
- If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
- If p.charAt(j) == '*': here are two sub conditions:
- if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
- if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':
- dp[i][j] = dp[i - 1][j] //in this case, a* counts as multiple a
- or dp[i][j] = dp[i][j - 2] // in this case, a* counts as empty
class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
int m = s.length();
int n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
// only when p is like "a*b*c*" could match empty str
for (int j = 1; j < n; j += 2) {
if (p.charAt(j) == '*' && dp[0][j - 1]) {
dp[0][j + 1] = true;
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') {
dp[i + 1][j + 1] = dp[i][j];
} else if (p.charAt(j) == '*') {
dp[i + 1][j + 1] = dp[i + 1][j - 1]; // match empty
if (p.charAt(j - 1) == s.charAt(i) || p.charAt(j - 1) == '.') {
dp[i + 1][j + 1] = dp[i + 1][j + 1] || dp[i][j + 1]; // match multiple
}
}
}
}
return dp[m][n];
}
}