using namespace std ;
//关于能否匹配可用递归的方式实现
//匹配上的情况
//1.下一位是*,分三种情况:
//1.1 matchCore(str+1,pattern) 模式串匹配成功,并尝试匹配下一字符
//1.3 matchCore(str,pattern+2) 模式串未匹配
//2.下一位不是*,则pattern对应为应该与str相等或者pattern的对应为为.
//matchCore(str+1, pattern + 1)
//3.对应为不匹配,返回false
class Solution {
public :
bool match(char* str, char* pattern)
{
if (str == NULL || pattern == NULL )
return false ;
return matchCore(str,pattern);
}
bool matchCore(char* str, char* pattern)
{
if (*str == '\0' &&*pattern == '\0' ) return true ; //迭代终止条件
if (*str != '\0' &&*pattern == '\0' ) return false ; //迭代终止条件
if (*(pattern + 1 ) == '*' )
{
if (*str == *pattern||(*pattern== '.' &&*str!= '\0' ))
return matchCore(str + 1 , pattern) || matchCore(str, pattern + 2 );
else
return matchCore(str, pattern + 2 );
}
if (*str == *pattern || (*pattern== '.' &&*str!= '\0' ))
return matchCore(str+ 1 ,pattern+ 1 );
return false ;
}
};
int main()
{
Solution so;
char * str = "aaa" ;
//char* pattern1 = "a*";
// cout << "str的长度是:" << strlen(str) << endl;
char * pattern1 = "ab*a*c*a" ;
char * pattern2 = "a.a" ;
char * pattern3 = "ab*a" ;
char * pattern4 = "aa.a" ;
char * pattern5 = "bbbba" ;
char * pattern6 = ".*a*a" ;
/*char* str = "aaa";
char* pattern1 = "bbbba";*/
//char* pattern1 = "";
//
cout << "pattern1 匹配的结果是: " << so.match(str, pattern1) << endl ;
cout << "pattern2 匹配的结果是: " << so.match(str, pattern2) << endl ;
cout << "pattern3 匹配的结果是: " << so.match(str, pattern3) << endl ;
cout << "pattern4 匹配的结果是: " << so.match(str, pattern4) << endl ;
cout << "pattern5 匹配的结果是: " << so.match(pattern5, pattern6) << endl ;
return 0 ;
}
转自 https://www.cnblogs.com/Czc963239044/p/6973831.html