题目:请实现一个函数用来匹配包含‘.’和‘*’的正则表达式。模式中的字符'.'表示任意一个字符,而‘*’表示它前面的字符可以出现任意次(含0次)。本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串“aaa”与模式“a.a”和“ab*ac*a”匹配,但与“aa.a”及“ab*a”均不匹配。
分析:如果模式中的字符ch是‘.’,那么它可以匹配字符串中的任意字符。如果模式中的字符ch不是'.'而且字符串中的字符也是ch,那么他们相互匹配。当字符串中的字符和模式中的字符相匹配时,接着匹配后面的字符。
当模式中的第二个字符不是‘*’时问题要简单很多。如果字符串中的第一个字符和模式中的第一个字符相匹配,那么在字符串和模式上都向后移动一个字符,然后匹配剩余的字符串和模式。如果字符串中的第一个字符和模式中的第一个字符不相匹配,则直接返回false。
当模式中的第二个字符是‘*’时,一个选择是在模式上向后移动两个字符。这相当于‘*’和它面前的字符被忽略掉了,因为‘*’可以匹配字符串中0个字符。如果模式中的第一个字符和字符串中的第一个字符相匹配时,则在字符串向后移动一个字符,而在模式上有两个选择:我们可以在模式上向后移动两个字符,也可以保持模式不变。
#include<iostream>
using namespace std;
bool matchCore(char *str,char *pattern)
{
if(*str=='\0' && *pattern=='\0')
return true;
if(*str!='\0' && *pattern=='\0')
return false;
if(*(pattern+1)=='*')
{
if(*pattern == *str || (*str!='\0' && *pattern == '.' ))
return matchCore(str,pattern+2) ||matchCore(str+1,pattern+2) || matchCore(str+1,pattern);
else
return matchCore(str,pattern+2);
}
if(*str==*pattern || (*str!='\0' && *pattern=='.'))
return matchCore(str+1,pattern+1);
return false;
}
bool match(char *str,char *pattern)
{
if(str==NULL || pattern==NULL)
return false;
return matchCore(str,pattern);
}
void Test(char *testName,char *str,char *pattern,bool expected)
{
cout<<testName<<" ";
if(expected == match(str,pattern))
cout<<"Passed.\n";
else
cout<<"Failed.\n";
}
int main()
{
Test("Test01", "", "", true);
Test("Test02", "", ".*", true);
Test("Test03", "", ".", false);
Test("Test04", "", "c*", true);
Test("Test05", "a", ".*", true);
Test("Test06", "a", "a.", false);
Test("Test07", "a", "", false);
Test("Test08", "a", ".", true);
Test("Test09", "a", "ab*", true);
Test("Test10", "a", "ab*a", false);
Test("Test11", "aa", "aa", true);
Test("Test12", "aa", "a*", true);
Test("Test13", "aa", ".*", true);
Test("Test14", "aa", ".", false);
Test("Test15", "ab", ".*", true);
Test("Test16", "ab", ".*", true);
Test("Test17", "aaa", "aa*", true);
Test("Test18", "aaa", "aa.a", false);
Test("Test19", "aaa", "a.a", true);
Test("Test20", "aaa", ".a", false);
Test("Test21", "aaa", "a*a", true);
Test("Test22", "aaa", "ab*a", false);
Test("Test23", "aaa", "ab*ac*a", true);
Test("Test24", "aaa", "ab*a*c*a", true);
Test("Test25", "aaa", ".*", true);
Test("Test26", "aab", "c*a*b", true);
Test("Test27", "aaca", "ab*a*c*a", true);
Test("Test28", "aaba", "ab*a*c*a", false);
Test("Test29", "bbbba", ".*a*a", true);
Test("Test30", "bcbbabab", ".*a*a", false);
}