KMP模式匹配 三(串)
Time Limit:1000MS Memory Limit:131072KB 64bit IO Format:%lld & %llu
Description
输入一个主串和一个子串,若匹配成功,则找出匹配的趟数和在子串在主串中的位置,若匹配不成功,则输出0
Input
输入两个字符串
Output
输出匹配的趟数和位置
Sample Input
ababcabcacbab abcac
Sample Output
3 6#include<stdio.h> #include <iostream> using namespace std; #include<stdlib.h> #include<string.h> #define N 1000005 int next[N],len1,len2,ans; char s1[N],s2[N]; void getnext(){ int k,j; len1=strlen(s1); next[0]=-1; j=0; k=-1; while(j<len1){ if(k==-1||s1[k]==s1[j]){ k++; j++; next[j]=k; } else k=next[k]; } return ; } void kmp() { int j,k; len2=strlen(s2); j=k=0; getnext(); while(j<len2&&k<len1){ if(k==-1||s2[j]==s1[k]){ j++; k++; } else {k=next[k];ans++;} if(k==len1) {cout<<ans<<" "<<j-len1+1<<endl;} } if(k!=len1) cout<<"0"<<endl; } int main(){ int i,j,k; ans=1; scanf("%s%s",s2,s1); kmp(); return 0; }