题目:请实现一个函数用来匹配包含'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但与"aa.a"及"ab*a"均不匹配。
#include <iostream>
using namespace std;
bool matchCore(const char* str, const char* pattern);
bool match(const char* str,const char* pattern)
{
//判断输入
if (str == nullptr&&pattern == nullptr)
return false;
return matchCore(str, pattern);
}
bool matchCore(const char* str,const char* pattern)
{
//当两个字符串都遍历到最后一个元素'\0'时表示相等
if (*str == '\0'&&*pattern == '\0')
return true;
//当一个到串尾一个还没遍历完时表示不相等
if (*str != '\0'&&*pattern == '\0')
return false;
//当模式字符串第二个元素为'*'时
if (*(pattern + 1) == '*')
{
//如果它们第一元素一样,则分3种情况:
//1.忽略'*'前面的元素,即返回matchCore(str,pattern+2)
//2.继续比较str的下一个元素,即返回matchCore(str+1,pattern)
//3.比较完这步,到下一步
if (*str == *pattern || (*pattern == '.'&&*str != '\0'))
{
return (matchCore(str, pattern + 2)) || matchCore(str + 1, pattern) || matchCore(str + 1, pattern + 2);
}
else
return matchCore(str, pattern + 2);
}
//当第一个元素相等时,跳到下一个元素的比较
if (*str == *pattern || *pattern == '.'&&*str != '\0')
return matchCore(str + 1, pattern + 1);
return false;
}
//输入测试
void Test1()
{
const char* str = "aaa";
const char* pattern = " ";
if (match(str, pattern))
printf("匹配!\n");
else
printf("不匹配\n");
}
void Test2()
{
const char* str = "aaa";
const char* pattern = "a.a";
if (match(str, pattern))
printf("匹配!\n");
else
printf("不匹配\n");
}
void Test3()
{
const char* str = "aaa";
const char* pattern = "ab*ac*a";
if (match(str, pattern))
printf("匹配!\n");
else
printf("不匹配\n");
}
void Test4()
{
const char* str = "aaa";
const char* pattern = "aaa.a";
if (match(str, pattern))
printf("匹配!\n");
else
printf("不匹配\n");
}
void Test5()
{
const char* str = "aaa";
const char* pattern = "ab*a";
if (match(str, pattern))
printf("匹配!\n");
else
printf("不匹配\n");
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}