题目描述
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
- ‘.’ 匹配任意单个字符
- ‘*’ 匹配零个或多个前面的那一个元素。所谓匹配,是要涵盖整个字符串 s的,而不是部分字符串。
示例 4:
输入:s = "aab" p = "c*a*b"
输出:true
解释:因为 '*' 表示零个或多个,这里 'c'为 0 个, 'a'被重复一次。因此可以匹配字符串 "aab"。
题解
使用动态规划方法。代码
bool charMatch(char s, char p) {
if (p == '.' || s == p) return true;
return false;
}
/* 使用方法:动态规划 */
bool isMatch(char * s, char * p){
int height = strlen(s);
int width = strlen(p);
bool** table = (bool**)malloc(sizeof(bool*) * (height+1));
if (table == NULL) { printf("Error\n"); return false; }
for (int i = 0; i <= height; i++) {
table[i] = (bool*)malloc(sizeof(bool) * (width+1));
if (table[i] == NULL) { printf("Error\n"); return false; }
}
table[0][0] = true;
for (int i = 1; i <= height; i++) table[i][0] = false;
for (int i = 1; i <= width; i++) {
if (p[i-1] == '*' && i >= 2) table[0][i] = table[0][i-2];
else table[0][i] = false;
}
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= width; j++) {
if (j >= 2 && p[j-1] == '*' ) {
if (charMatch(s[i-1], p[j-2]))
table[i][j] = table[i-1][j] || table[i][j-2];
else table[i][j] = table[i][j-2];
} else if (charMatch(s[i-1], p[j-1])) {
table[i][j] = table[i-1][j-1];
} else {
table[i][j] = false;
}
}
}
return table[height][width];
}
来源:LeetCode-10