题目
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", "c*a*b") → true
答案
定义(Note that in this definition string starts with index 1, not 0)
dp[i][j] = is s[1...i] matched by p[1...j] ?
Basecases:
dp[0][0] = true, empty text matches empty pattern没毛病...
dp[i][0] = false, for all i >=1, when text is non-empty, and pattern is empty, there is no match
dp[0][j] = true if pattern is in the form of a1a2a3*.....(whera a1,a2,a3 is a character), false otherwise
Recursive cases:
If s[i] == p[j] or p[j] == '.' -> dp[i][j] = dp[i-1][j-1]
if p[j] = '*'
dp[i][j] = dp[i][j-2] (matches 0 character in s)
if p[j-1] == s[i] -> dp[i][j] = dp[i][j] || dp[i-1][j]
class Solution {
public boolean isMatch(String s, String p) {
int s_len = s.length(), p_len = p.length();
boolean[][] dp = new boolean[s_len + 1][p_len + 1];
// Empty text matches empty empty pattern
dp[0][0] = true;
// Empty pattern matches no string with len > 0
for(int i = 1; i <= s_len; i++)
dp[i][0] = false;
// Non-empty pattern can sometimes match empty string
for(int j = 1; j <= p_len; j++) {
char pattern_c = p.charAt(j - 1);
if(pattern_c == '*') {
dp[0][j] = dp[0][j - 2];
}
else {
dp[0][j] = false;
}
}
for(int i = 1; i <= s_len; i++) {
for(int j = 1; j <= p_len; j++) {
char pattern_c = p.charAt(j - 1);
if(pattern_c == '*') {
// x* doesn't match anything, if this work, good!
dp[i][j] = dp[i][j - 2];
// x* matched x, if previou string also match, good!
if(p.charAt(j - 2) == s.charAt(i - 1) || p.charAt(j - 2) == '.')
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
else if(pattern_c == '.' || pattern_c == s.charAt(i - 1)) {
// if current char matches and previous string and pattern also matches, good!
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[s_len][p_len];
}
}