Thursday, February 11, 2021, the weather is fine [Do not lament the past, do not waste the present, do not fear the future]
Contents of this article
1. Introduction
Sword refers to Offer 19. Regular expression matching
2. Dynamic programming
This question is still very difficult. I just looked at the solution of this big guy directly. I feel that as long as I spend some time carefully thinking about it, the idea can still be clear. Here is the code:
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size();
int n = p.size();
vector<vector<bool>> dp(m+1,vector<bool>(n+1,false));
for(int i=0;i<=m;++i){
for(int j=0;j<=n;++j){
// 分成空正则和非空正则两种
if(j==0) dp[i][j] = i==0;
// 非空正则分为两种情况 * 和 非 *
// 非 * 的情况(当j=n时,j-1表示正则串p的最后一个字符)
else if(p[j-1]!='*'){
if(i>0 && (p[j-1]==s[i-1] || p[j-1]=='.')){
dp[i][j] = dp[i-1][j-1];
}
}
// * 的情况
else if(p[j-1]=='*'){
// 碰到 * 了,分为考虑和不考虑两种情况
// 不考虑 *
if(j>=2){
dp[i][j] = dp[i][j-2];
}
// 考虑 *(当i=m时,i-1表示字符串s的最后一个字符))
if(i>=1 && j>=2 && (s[i-1]==p[j-2] || p[j-2]=='.')){
dp[i][j] = dp[i][j] || dp[i-1][j];
}
}
}
}
return dp[m][n];
}
};
references
"Sword Finger Offer Second Edition"
https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/solution/zhu-xing-xiang-xi-jiang-jie-you-qian-ru-shen-by-je/