面试题19:正则表达式匹配
题目:请实现一个函数用来匹配’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但与"aa.a"和"ab*a"均不匹配。
#include <iostream>
using namespace std;
bool match(char* str, char* pattern);
bool matchCore(char* str, char* pattern);
bool match(char* str, char* pattern)
{
if(str== nullptr||pattern== nullptr)
return false;
return matchCore(str,pattern);
}
bool matchCore(char*str, char* pattern)
{
//当两字符达到'\0'时,则完成匹配
if(*str=='\0'&&*pattern=='\0')
return true;
//当两字符串长度不同时,无法匹配
if((*str=='\0'&&*pattern!='\0')||(*str!='\0'&&*pattern=='\0'))
return false;
//如果两字符相等或者其中一个等于'.'则检索下一个字符
if((*str==*pattern&&*str!='*')||*str=='.'||*pattern=='.')
return matchCore(str+1,pattern+1);
//如果两个字符相等且为*则移动到与'*'前面字符相异的第一个字符进行比较
// 这里假设'*'不能放在第一个字符
else if(*str==*pattern&&*str=='*')
{
char sample=*(str-1);
int count1=0;
int count2=0;
while (*(str++)==sample)
count1++;
while (*(pattern++)==sample)
count2++;
return matchCore(str+count1+1,str+count2+1);
}
//如果该处不相等且其一为'*',则将带'*'的字符串往后移动两个位置
else if ((*str!=*pattern)&&*str=='*')
return matchCore(str+2,pattern);
else if ((*str!=*pattern)&&*pattern=='*')
return matchCore(str,pattern+2);
//最后一种情况是该处字符不相等且都不是'*'
else
{
if(*(str+1)=='*')
return matchCore(str+2,pattern);
if(*(pattern+1)=='*')
return matchCore(str,pattern+2);
else
return false;
}
}
int main() {
bool result;
char a[4]={'a','a','a'};
char b[8]={'a','b','*','a','c','*','a'};
char c[5]={'a','b','*','a'};
result=match(c,b);
cout<<result<<endl;
std::cout << "Hello, World!" << std::endl;
return 0;
}