0% found this document useful (0 votes)
7 views2 pages

KMP

The document contains two main algorithms for string matching: the Knuth-Morris-Pratt (KMP) algorithm and the Rabin-Karp (RK) algorithm. The KMP algorithm preprocesses a pattern to create a next array for efficient searching, while the RK algorithm uses hashing to find occurrences of a pattern in a text. Both algorithms are implemented in C++ and C, respectively, with the KMP algorithm also handling multiple test cases.

Uploaded by

dingtaodtdt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

KMP

The document contains two main algorithms for string matching: the Knuth-Morris-Pratt (KMP) algorithm and the Rabin-Karp (RK) algorithm. The KMP algorithm preprocesses a pattern to create a next array for efficient searching, while the RK algorithm uses hashing to find occurrences of a pattern in a text. Both algorithms are implemented in C++ and C, respectively, with the KMP algorithm also handling multiple test cases.

Uploaded by

dingtaodtdt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<bits/stdc++.

h>
using namespace std;
#define N 5000004
char s[N],a[N],b[N];
int nxt[N],leap[N];
void getnext(char *s)
{
int len=strlen(s);
memset(nxt,0,sizeof(nxt));
for(int i=1;i<len;i++){
int j=nxt[i];
while(j&&s[i]!=s[j]) j=nxt[j];
nxt[i+1]=(s[i]==s[j]) ? j+1 :0;
}
}
void kmp(char *s,char *s2)
{
memset(leap,0,sizeof(leap));
int j=0,len=strlen(s),len2=strlen(s2);
for(int i=0;i<len;i++){
while(j&&s[i]!=s2[j]) j=nxt[j];
if(s[i]==s2[j]) j++;
if(j==len2) leap[i-len2+1]=1;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%s%s%s",s,a,b);
int len=strlen(a);
getnext(a);
kmp(s,a);
//for(int i=0;s[i];i++) printf("%d ",leap[i]);
for(int i=0;s[i];){
if(leap[i]){
printf("%s",b);
i+=len;
}
else{
printf("%c",s[i]);
i++;
}
}
printf("\n");
}
return 0;
}

hash����
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXN 100
const int d=128;
const int q=6999997;
int RK(char *T,char *pat)
{
int n=strlen(T),m=strlen(pat);
if(n<m) return -2;
int i,s,t=0,p=0,h=1;
for(i=1; i<m; i++) h=(h*d) % q; //h=d^m-1
for(i=0; i<m; i++)
{
p = ( d*p+pat[i] ) % q; //p[m]
t = ( d*t+T[i] ) % q; //t[m]
}
int ans=0;
for(s=0; s<=n-m; s++)
{
if(p==t)
{
ans++;
}
if(s<n-m)
t = ( d*(t-h*T[s]) + T[s+m] ) % q; //t[s+1]
}
return ans;
}
char s1[MAXN],s2[MAXN];
int main()
{
while(scanf("%s%s",s1,s2))
{
printf("%d\n",RK(s1,s2));
}
return 0;
}

You might also like