题目描述
问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(字符由英文字母和数字0-9组成,不区分大小写。下同)
?:匹配1个字符
输入描述:
先输入一个带有通配符的字符串,再输入一个需要匹配的字符串
输出描述:
返回匹配的结果,正确输出true,错误输出false
示例1
输入:te?t*.*
txt12.xls
输出:false
#include <iostream>
#include <string>
using namespace std;
//字符串通配符
bool test(const char* tmp, const char* str)
{
//当两个字符串同时结束时候,返回真
if (*tmp == '\0' && *str == '\0')
{
return true;
}
//当其中有一个字符串首先结束,返回假
if (*tmp == '\0' || *str == '\0')
{
return false;
}
//'?'通配一个字符,继续递归下一个字符
if (*tmp == '?')
{
return test(tmp + 1, str + 1);
}
//'*'通配不计数字符,直接递归str的下一个字符
else if (*tmp == '*')
{
return test(tmp + 1, str) || test(tmp + 1, str + 1) || test(tmp, str + 1);
}
else if (*tmp == *str)
{
return test(tmp + 1, str + 1);
}
return false;
}
int main()
{
string tmp, str;
while (cin >> tmp >> str)
{
bool ret = test(tmp.c_str(), str.c_str());
if (ret)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
system("pause");
return 0;
}