-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
110 lines (83 loc) · 2.18 KB
/
Copy pathKMP.cpp
File metadata and controls
110 lines (83 loc) · 2.18 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <vector>
#include <iostream>
#include <string>
#include "KMP.h"
using namespace std;
vector<int> buildLps(string s) //creates the lps array needed for KMP algorithm
{
int j = 0; int i = 1; bool isMatch = false;
vector<int> returnVal(s.length(), 0);
while (i < s.length())
{
if (isMatch) //continued match
{
if (s[i] == s[j])//match continues
{
returnVal.at(i) = j + 1;
i++; j++; isMatch = true;
}
else //match over
{
do
{
j = returnVal.at(j - 1);
} while (!((j == 0) || (s[i] == s[j])));
isMatch = false;
}
}
else
{
if (s[i] == s[j])//match starts
{
returnVal.at(i) = j + 1;
i++; j++; isMatch = true;
}
else //keep trying
{
i++;
isMatch = false;
}
}
}
return returnVal;
}
int patternInText(string pattern, string text) //returns the location of the start of match, -1 if no match exists
{
vector<int> lps = buildLps(pattern);
int i = 0; int j = 0;
while (i < text.length())
{
if (text[i] == pattern[j])
{
while (text[i] == pattern[j])
{
i++; j++;
if (j == pattern.length()) //we found it!
{
return (i - pattern.length());
}
}
j = lps.at(j-1); //when no longer matching
}
else
{
i++;
}
}
return -1;
}
void numOfOccurrances(string pattern, string text)
{
int isFoundAt = -1;
int occurrances = 0;
do
{
isFoundAt = patternInText(pattern, text);
if (isFoundAt != -1)
{
occurrances++;
text = text.substr(isFoundAt + pattern.length());
}
} while (isFoundAt != -1);
cout << "Occurrences: " << occurrances << endl;
}