串的模式匹配
实现串的BF模式匹配算法,统计在匹配过程中总的字符比较次数,当主串剩余部分不足子串长度时,停止比较。
Input
输入包含两行,第一行为主串s,第二行为子串t。
Output
输出包含两行,第一行为子串在主串中的位置,如果失配,返回0值;第二行为匹配过程中总的字符比较次数。
Sample Input
abacd
ac
Sample Output
3
5
#include<stdio.h>
#include<string.h>
int main(){
char s[999999],t[999999];
while(gets(s)&&gets(t)){
long long int i=0,j=0,index,count=0;
while(i<strlen(s)&&j<strlen(t)){
/* if(strlen(s)<strlen(t)){ //如果模式串大于主串,输出0 0;
index = -1;
break;
}
*/
if(s[i]==t[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
count++;
}
if(j>=strlen(t)){
index=i-strlen(t);
}
else {
index=-1;
}
// printf("%d %d\n",strlen(s),strlen(t));
printf("%d\n",index+1);
printf("%d",count);
}
return 0;
}