MCPcopy Create free account
hub / github.com/SR-Sunny-Raj/Hacktoberfest2021-DSA / computeLPSArray

Function computeLPSArray

09. String/KMP_Algorithm.cpp:4–40  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2using namespace std;
3
4void computeLPSArray(string pat, int M, int *lps)
5{
6 // length of the previous longest prefix suffix
7 int len = 0;
8
9 lps[0] = 0; // lps[0] is always 0
10
11 // the loop calculates lps[i] for i = 1 to M-1
12 int i = 1;
13 while (i < M)
14 {
15 if (pat[i] == pat[len])
16 {
17 len++;
18 lps[i] = len;
19 i++;
20 }
21 else // (pat[i] != pat[len])
22 {
23 // This is tricky. Consider the example.
24 // AAACAAAA and i = 7. The idea is similar
25 // to search step.
26 if (len != 0)
27 {
28 len = lps[len - 1];
29
30 // Also, note that we do not increment
31 // i here
32 }
33 else // if (len == 0)
34 {
35 lps[i] = 0;
36 i++;
37 }
38 }
39 }
40}
41// Prints occurrences of txt[] in pat[]
42void KMPSearch(string pat, string txt)
43{

Callers 1

KMPSearchFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected