-
Notifications
You must be signed in to change notification settings - Fork 0
/
pAq2.cpp
77 lines (65 loc) · 1.3 KB
/
pAq2.cpp
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
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
void generateLPS(int m, char* pattern, int*LPS)
{
int suffix = 0;
for (int c=1; c<m; c++) //start at 1 because LPS[0]=0
{
if (pattern[c]==pattern[m])
{
suffix++;
LPS[c]=suffix;
}
else
{
if (suffix==0)
{
LPS[c]=0;
}
else
{
suffix = LPS[suffix-1];
c--; //stay on the index
}
}
}
}
void KMP(char* text, char* pattern)
{
int m = strlen(pattern);
int n = strlen(text);
int LPS[m] = {0};
generateLPS(m, pattern, LPS);
int t=0;
int p=0;
while (t<n)
{
if (pattern[p]==text[t])
{
p++;
t++;
}
if (p==m)
{
cout<<"Pattern found at index: "<<t-p<<endl;
p=LPS[p-1];
}
else if (pattern[p]!=text[t] && t<n)
{
//mismatch after p matches
if (p!=0)
p=LPS[p-1];
else
t++;
}
}
}
int main()
{
char Text[] = "baabaababaabaaba";
char Pattern[] = "abaa";
KMP(Text, Pattern);
return 0;
}