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
解题思路:dp[i][j]表示s的前i个字符和p的前j个字符能否匹配。根据正则表达式的匹配规则进行状态转移即可。
class Solution { public: bool isMatch(string s, string p) { bool dp[1010][1010]; int n = s.length(); int m = p.length(); memset(dp, false, sizeof(dp)); dp[0][0] = true; for(int i = 1; i <= m; ++i) { if(p[i-1] == '*') { if(i == 1) { dp[0][i] = true; } else { if(p[i-2] == '*') { dp[0][i] |= dp[0][i-1]; } else { dp[0][i] |= dp[0][i-2]; } } } else { dp[0][i] = false; } } for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { if(p[j-1] == '*') { if(j - 2 >= 0) { int k = i; dp[i][j] |= dp[i][j-2]; while(k > 0 && (s[k-1] == p[j-2] || p[j-2] == '.')) { dp[i][j] |= dp[k-1][j-2]; --k; } } else { dp[i][j] |= dp[i][j-1]; } } else if(p[j-1] == '.') { dp[i][j] |= dp[i-1][j-1]; } else { if(s[i-1] == p[j-1]) { dp[i][j] |= dp[i-1][j-1]; } else { dp[i][j] = false; } } } } return dp[n][m]; } };