-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkmp.cpp
85 lines (71 loc) · 1.47 KB
/
kmp.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
78
79
80
81
82
83
84
85
#include <bits/stdc++.h>
using namespace std;
void implementAuxArray(int* ptr, string pattern, int patLen)
{
int m = 0;
int i = 1;
while(i < patLen)
{
if (pattern.at(i) == pattern.at(m))
{
m++;
ptr[i] = m;
i++;
}
else if (pattern.at(i) != pattern.at(m) && m != 0)
{
m = ptr[m-1];
}
else
i++;
}
}
int main()
{
string input="acabacaba", output="acfacabacabacacdk";
//cin >> input >> output;
string text = input, pattern = output;
if(input.length() < output.length())
{
text = output;
pattern = input;
}
int patLen = pattern.length();
int aux[patLen] = {};
int *auxPtr = aux;
implementAuxArray(auxPtr, pattern, patLen);
for (int i = 0; i < patLen; ++i)
{
cout << auxPtr[i] <<" ";
}
cout << endl << text << " " << pattern << endl;
int textIndex = 0,patIndex = 0, patLenMatching = 0;
while(textIndex < text.length())
{
if( text.at(textIndex) != pattern.at(patIndex))
{
if(patIndex == 0)
{
textIndex++;
}
else
{
patIndex = auxPtr[patIndex-1];
}
}
else
{
textIndex++;
patIndex++;
if(patLenMatching < patIndex)
patLenMatching = patIndex;
if(patIndex == patLen) break;
}
}
if(patIndex == patLen)
cout << "Eureka! pattern existing in the given text" << endl;
else
cout << "minimum number of operations to perform for converting text to pattern: "<< text.length() - patLenMatching << endl;
//cout << "patIndex: "<<patIndex<<", patLenMatching: "<<patLenMatching<<endl;
return 0;
}