题目:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
代码(没有进行提交测试,只保留思想)
#include<iostream>
#include<vector>
#include<list>
#include<fstream>
#include<string>
#include<set>
#include<map>
#include<algorithm>
#include<stack>
#include <typeinfo>
#include<bitset>
#include<cstdio>
#include <stdarg.h>
#include<functional>
using namespace std;
bool is_match(string &s1,int len1,string &s2,int len2){
int **ptr = new int*[len2];
for (int i = 0; i < len2; i++){
ptr[i] = new int[len1];
memset(ptr[i],0,sizeof(int)*len1);//每一行都有len1个元素
}
//初始化
if (s1[0] == s2[0])ptr[0][0] = 1;
for (int i = 1; i < len2; i++){
if (ptr[i - 1][0] == 1 && s2[i] == '*')ptr[i][0] = 1;
}
for (int i = 1; i < len2;i++){
for (int j = 1; j < len1;j++){
if (s1[j] == s2[i]){//两者相等
if (ptr[j - 1][i - 1] == 1)ptr[j][i] = 1;
}
else{//两个字符不想等
if (s2[i] == '?'){
if (ptr[j - 1][i - 1] == 1)ptr[j][i] = 1;
}
else{//s2[i] == '*'
if (ptr[i - 1][j - 1] == 1){
for (int k = j; k < len1; k++)ptr[i][k] = 1;
break;//直接跳到下一行
}
}
}
}
}
for (int i = 0; i < len2; i++)delete[]ptr[i];
delete[]ptr;
return ptr[len2][len1];
}
int main(void){
ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
string str1, str2;
while (fin>>str1>>str2){
int size1 = str1.size();
int size2 = str2.size();
if (size1 == 0 || size2 == 0)cout << "false" << endl;
if(is_match(str1,size1,str2,size2)) cout<<"yes"<< endl;//str1是不带*和?的串
else cout <<"false"<< endl;
}
}
这样的通配符匹配算法有两种方式:
第一种:
'*' Matches any sequence of characters (including the empty sequence).第二种:
'*' Matches zero or more of the preceding element.
首先看第一种的解决办法,假设我们有两个串,abcdacd和a*d?cd,那么利用动态规划算法可以解决,
假设ptr[i][j]表示包含第一个串的下标为i的元素和第二串下标为j的匹配情况,那么我们就有下面的表格:
当*只能匹配它前一个字符的任意数量时,那么在不含通配符的串中,只要ptr[i-1][j]==s1[i-1],那么对应的表格的位置都是匹配的,如下图
若有疑问,可发邮件讨论!!!!!