-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab12_Q4.cpp
More file actions
77 lines (63 loc) · 1.53 KB
/
Lab12_Q4.cpp
File metadata and controls
77 lines (63 loc) · 1.53 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
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void toLowerCase(string& str) {
for (int i = 0; i < str.length(); i++) {
str[i] = tolower(str[i]);
}
}
void computeLPSArray(const string& pattern, int* lps) {
int m = pattern.length();
int length = 0;
lps[0] = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(const string& text, const string& pattern) {
string textLower = text;
string patternLower = pattern;
toLowerCase(textLower);
toLowerCase(patternLower);
int n = textLower.length();
int m = patternLower.length();
int lps[m];
computeLPSArray(patternLower, lps);
int i = 0;
int j = 0;
while (i < n) {
if (patternLower[j] == textLower[i]) {
i++;
j++;
}
if (j == m) {
cout << "Pattern found at index " << i - j << endl;
j = lps[j - 1];
} else if (i < n && patternLower[j] != textLower[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}
int main() {
string text = "Data Structures";
string pattern = "data";
KMPSearch(text, pattern);
return 0;
}