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毫痕,但是現(xiàn)在會TLE,必須祭出DP大法啦邻遏。
注意必須預(yù)處理j = 0的情況诗良!考慮s = "", p = "a*"汹桦,如果沒有預(yù)處理,則結(jié)果會返回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];
}
}