-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathcode_2.cpp
82 lines (75 loc) · 1.73 KB
/
code_2.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
//
// code_2.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
// calculating Longest prefix AND suffix
void computeLPSArray(string pattern, int* lps) {
long M = pattern.length();
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
}
bool search(string text , string pattern) {
long M = pattern.length();
long N = text.length();
bool flag = false;
int lps[M]; // for longest prefix and suffix
computeLPSArray(pattern, lps);
int i = 0; // index for txt[]
int j = 0; // index for pat[]
while (i < N) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == M) {
cout << "Pattern found at index\t:\t" << i-j << "\n";
j = lps[j - 1];
flag = true;
}
else if (i < N && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
}
else {
i++;
}
}
}
return flag;
}
int main() {
string text , pattern;
cout << "\nEnter Text\t\t\t\t:\t";
getline(cin , text);
cout << "\nEnter Pattern\t\t\t:\t";
getline(cin , pattern);
cout << endl;
if ( !search(text ,pattern) ) {
cout << "\nPattern Not Found\n";
}
cout << endl;
return 0;
}