题目描述
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配。
方法一:递归
书上代码
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str == NULL || pattern == NULL)
return false;
char *pchar = str;
int len1 = 0;
int len2 = 0;
for(; *pchar != '\0'; pchar++)
len1++;
for(pchar = pattern; *pchar != '\0'; pchar++)
len2++;
return isValid(str, pattern, len1, len2) ? process(str, pattern, 0, 0, len1, len2) : false;
}
bool isValid(char* str, char* pattern, int len1, int len2)
{
for(int i = 0; i < len1; i++)
if(str[i] == '*' || str[i] == '.')
return false;
for(int i = 0; i < len2; i++)
if(pattern[i] == '*' && (i == 0 || pattern[i - 1] == '*'))
return false;
return true;
}
bool process(char* str, char* pattern, int si, int pi, int len1, int len2)
{
if(pi == len2)
return si == len1;
if(pi + 1 == len2 || pattern[pi] != '*')
return si != len1 && (pattern[pi] == str[si] || pattern[pi] == '.')
&& process(str, pattern, si + 1, pi + 1, len1, len2);
while(si != len1 && (str[si] == pattern[pi] || pattern[pi] == '.'))
{
if(process(str, pattern, si, pi + 2, len1, len2))
return true;
si++;
}
return process(str, pattern, si, pi + 2, len1, len2);
}
};
未能AC所有实例。(为什么?)
别人的代码
https://www.nowcoder.com/profile/3639006/codeBookDetail?submissionId=19276572
class Solution {
public:
bool match(char* str, char* pattern)
{
if (*str == '\0' && *pattern == '\0')
return true;
if (*str != '\0' && *pattern == '\0')
return false;
//if the next character in pattern is not '*'
if (*(pattern+1) != '*')
{
if (*str == *pattern || (*str != '\0' && *pattern == '.'))
return match(str+1, pattern+1);
else
return false;
}
//if the next character is '*'
else
{
if (*str == *pattern || (*str != '\0' && *pattern == '.'))
return match(str, pattern+2) || match(str+1, pattern);
else
return match(str, pattern+2);
}
}
};
方法二:动态规划(可省去递归过程中很多重复的计算)
见程序员代码面试指南P297