-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp
86 lines (82 loc) · 1.46 KB
/
kmp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//************************法一***********************
#include <iostream>
#include <cstring>
#define MAX 1000+5
using namespace std;
char p[MAX],s[MAX];
int Next[MAX],ls,lp;
void setNext() {
int j = 0;
for(int i = 2; i <= lp; i++) {
while(j && p[i]!=p[j+1]) j = Next[j];
if(p[j+1] == p[i]) j++;
Next[i] = j;
}
}
void kmp() {
ls = strlen(s+1);
lp = strlen(p+1);
setNext();
int j = 0;
for(int i = 1; i <= ls; i++) {
while(j>0 && p[j+1] != s[i]) j = Next[j];
if(p[j+1] == s[i]) j++;
if(j==lp) {
cout<<i-j+1<<endl;
j = Next[j];
}
}
}
int main() {
cin>>(s+1);
cin>>(p+1);
kmp();
return 0;
}
//***********************法二***************************
#include <iostream>
#include <string.h>
#include <stdio.h>
#define MAX 1000
using namespace std;
int lens ;
int lenp ;
void getNext(char* p,int* Next) {
Next[1] = 0;
int i = 1, j = 0;
while( i < lenp ) {
if(j==0 || p[i]==p[j]) {
i++; j++;
Next[i] = j;
}
else {
j = Next[j];
}
}
}
char* kmp(char* s,int pos,char* p) {
int Next[MAX+10];
getNext(p,Next);
int i = pos, j = 1;
while(i <= lens && j <= lenp) {
if(j ==0 || s[i] == p[j]) {
i++; j++;
}
else {
j = Next[j];
}
}
if(j == lenp + 1) {
return s+ (i - lenp);
}
return NULL;
}
int main() {
char p[MAX],s[MAX];
gets(s+1);
gets(p+1);
lens = strlen(s+1);
lenp = strlen(p+1);
cout<<kmp(s,1,p)<<endl;
return 0;
}