子串模糊匹配
从字符串string开始完整匹配子串sub,返回匹配到的字符个数。
sub中如果出现’?‘表示可以匹配一到三个除’\0’以外的任意字符。
如果sub还有找不到匹配的字符,则说明不能完整匹配。
如果能完整匹配,返回匹配到的字符个数,如果有多种匹配方式,返回匹配字符数最少的那个,如果不能完整匹配,返回-1
输入描述:
第一行输入字符串string,长度小于10000
第二行输入子串sub,长度小于100
输出描述:
从string开头位置完整匹配sub,匹配到的字符个数。
输入例子1:
abcdefg
a?c
输出例子1:
3
输入例子2:
aabcddefg
a?c
输出例子2:
4
输入例子3:
aabcddefg
b?e
输出例子3:
-1
输入例子4:
aabcddefg
a?d
输出例子4:
5
解答:
#include<iostream>
#include<cstring>
using namespace std;
int func(char*str , char* sub)
{
int i=0,j=0;//i j 分别用来表示str、sub比较时的下标
int x = 0; //x用来表示?已经代替的字符个数
int count = 0;//count表示满足的字符个数
while(i<strlen(str) && j<strlen(sub))
{
if(str[i] == sub[j])
{
i++;
j++;
count++;
x = 0;
}
else if(sub[j] != '?')
break;
else //sub[j] = '?'
{
while(str[i] != sub[j] && x<3)
{
i++;
if(!x) j++; //第一次x=0时,sub的下标也向后移动一个
x++;
count++;
}
x=0;
}
}
if(j == strlen(sub))
return count;
else
return -1;
}
int main()
{
char str[1005];
char sub[105];
cin>>str>>sub;
cout<<func(str,sub);
return 0;
}