leetdode10 正则表达式匹配
问题描述:
问题分析:
用dp[i][j]表示s[0,i)和p[0,j)是否匹配。dp[0][0]=true;然后开始递推,递推关系为:
if(j>1&&p[j-1]=='*'&& the value of '*' is 0) dp[i][j]=dp[i][j-2];
if(j>1&&p[j-1]=='*'&& the value of '*' is 1 at least) dp[i][j]=dp[i-1][j]; condition: s[i-1]==p[j-2]||p[j-2]=='.'
if(s[i-1]==p[j-1]||p[j-1]=='.') dp[i][j]=dp[i-1][j-1];
代码实现:
//递推型动态规划 #include<stdio.h> #include<string.h> char s[1000],p[1000]; bool isMatch(char * s, char * p) { if(!s) return true; int sl = strlen(s); int pl = strlen(p); bool dp[1000][1000]; //无奈,vc++数组不支持变量做大小 memset(dp, 0, sizeof(dp)); dp[0][0]=true; for (int i = 0; i<=sl; i++) { for (int j=1; j <=pl;j++) { if (j>1 && p[j-1]=='*') { dp[i][j] = dp[i][j-2] || (i>0 && (p[j-2]=='.' || p[j-2]==s[i-1]) && dp[i-1][j]); } else { dp[i][j] = i>0 && (p[j-1] == '.' || p[j-1] == s[i-1]) && dp[i-1][j-1]; } } } return dp[sl][pl]; } int main() { while(scanf("%s%s",s,p)==2) printf("%d\n",isMatch(s,p)); return 0; }
运行结果: