本文共 4037 字,大约阅读时间需要 13 分钟。
Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
给定一个字符串s和匹配的模板p,使用“.”和“*”,实施正则表达式的匹配
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).“.”匹配单个字母
“*”匹配零个或者多个该字符之前的元素。 这种匹配应该包括整个输入的字符串,而不是局部Note:
Input:
s = “aa” p = “a” Output: false Explanation: “a” does not match the entire string “aa”. Example 2:Input:
s = “aa” p = “a*” Output: true Explanation: ‘*’ means zero or more of the preceding element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”. *表示有零个或者多个元素a,因此,通过一次重复,变成了aa Example 3:Input:
s = “ab” p = “." Output: true Explanation: ".” means “zero or more (*) of any character (.)”. Example 4:Input:
s = “aab” p = “cab” Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches “aab”. Example 5:Input:
s = “mississippi” p = “misisp*.” Output: false总结:如果按照正向从左往右进行分析,会出现很多的分支情况,而且会有很多的特例。
bool isMatch4(char *s,char *p){ if(!*s || !*p) { return false; } //建立对应的二维数组 int plen = strlen(p),slen = strlen(s); bool dp[slen+1][plen+1]; //将dp[0][0]赋予true,将其余各项默认为false dp[0][0] = 1; for(int i =0; i < slen + 1;i ++) { for(int j = 0;j < plen + 1;j ++) { dp[i][j] = false; } } //将第零行先赋值 for(int j = 1;j < plen +1 ;j ++) { if(*(p+j-1) == '*') { dp[0][j] = dp[0][j -2]; } } for(int i = 1;i < slen + 1;i ++) { for(int j = 1;j < plen + 1;j ++) { //情况一,S末位的字符和P末位的字符匹配成功 if(*(s + i - 1) == *(p + j - 1) || *(p+j-1) == '.') { dp[i][j] = dp[i - 1][j - 1]; } else if(*(p + j - 1)=='*') { //如果*号之前字母和text中的字母相匹配,那么可以直接将a退出对应的匹配中 if(*(p + j - 2) == *(s + i - 1) || *(p + j - 2) == '.') { dp[i][j] = dp[i - 1][j] | dp[i - 1][j - 2] | dp[i][j - 2]; } else { //扫描遇见了空格取决于其之前两个位置的字符,能否成功的匹配 dp[i][j] = dp[i][j - 2]; } } } } //输出对应的矩阵,验证一下 printf("\n"); for(int i =0; i < slen + 1;i ++) { for(int j = 0;j < plen + 1;j ++) { printf("%d ",dp[i][j]); } printf("\n"); } return dp[slen][plen];}
转载地址:http://pggpb.baihongyu.com/