给定一个字符串串A,A中只包含小写字母
再给定一个串B,B中包含小写字母和' . '和' * ', 其中' . '可以替换为任意字符,' * '必定跟在一个' . '或者一个字母的后面,代表'.'或者字母可以重复0或多次。问B去匹配A,输出第一次匹配的开头下标。
例如:
A:aab B:ab 输出1
A:cabc B:b. 输出2
A:aaab B:a*b 输出0
A:bbcdef B:b.*ef 输出0
目前只想到枚举开始匹配的起点+暴力dfs。如果各位有什么想法欢迎评论区提出。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <time.h>
#include <map>
#include <set>
#define mem(a,x) memset(a,x,sizeof(a))
#define gi(x) scanf("%d",&x)
#define gi2(x,y) scanf("%d%d",&x,&y)
#define gi3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define gll(x) scanf("%lld",&x)
#define gll2(x,y) scanf("%lld%lld",&x,&y)
#define random(x) (rand()%x)
using namespace std;
const double eps=1e-8;
typedef long long ll;
const int MAXN=100005;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
bool dfs(string pattern,int idp,string subject,int ids){
if(idp==pattern.size())return true;
if(ids==subject.size())return false;
if(pattern[idp]!='.'){//是确定的
if(idp+1==pattern.size()||pattern[idp+1]!='*'){
if(pattern[idp]==subject[ids]){
return dfs(pattern,idp+1,subject,ids+1);
}
else return false;
}
int i=ids;
while(i<subject.size()&&subject[i]==pattern[idp]){
i++;
}
int t=i-1;
bool flag=false;
for(int j=ids;j<=t+1;j++){
flag=dfs(pattern,idp+2,subject,j);
if(flag==true)return true;
}
return false;
}
else{
if(idp+1==pattern.size()||pattern[idp+1]!='*'){
return dfs(pattern,idp+1,subject,ids+1);
}
else{
bool flag=false;
for(int i=ids;i<=subject.size();i++){
flag=dfs(pattern,idp+2,subject,i);
if(flag==true)return true;
}
return false;
}
}
}
int search(string pattern,string subject){
for(int i=0;i<subject.size();i++){
bool flag=dfs(pattern,0,subject,i);
if(flag)return i;
}
return -1;
}
int main(int argc, char *argv[]) {
//TEST CASE
cout<<(search("a","a")==0)<<endl;
cout<<(search("b","s")==-1)<<endl;
cout<<(search("bba","abbacbbac")==1)<<endl;
cout<<(search("bbs","abbabbabsb")==-1)<<endl;
cout<<(search("a*b","aaaab")==0)<<endl;
cout<<(search("bb","baba")==-1)<<endl;
cout<<(search("bba.z","aasbbatzbba")==3)<<endl;
cout<<(search("bba.*z","aasbbattzbba")==3)<<endl;
cout<<(search("a*aab","ab")==-1)<<endl;
}