-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPattern-Matching-KMP-Algorithm.cpp
77 lines (70 loc) · 1.89 KB
/
Pattern-Matching-KMP-Algorithm.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
#include <bits/stdc++.h>
using namespace std;
// Compute the LPS array
void computeLpsArray(string &p, int m, vector<int> &lps) {
// Length of the previous longest prefix suffix
int len = 0, i = 1;
// lps[0] is always 0
while(i < m) {
// If the characters match
if(p[i] == p[len]) {
// Increment the length
len++;
// Store the length
lps[i] = len;
// Increment the index
i++;
// If the characters don't m atch
} else {
// Check if the length is not 0
if(len != 0) {
// If the length is not 0
// Update the length
len = lps[len - 1];
// If the length is 0
} else {
// Update the index
i++;
}
}
}
}
// Find the pattern in the string
bool findPattern(string p, string s)
{
// Get the size of the strings
int n = s.size(), m = p.size();
// Compute the LPS array
vector<int> lps(m, 0);
computeLpsArray(p, m, lps);
// Find the pattern
int i = 0, j = 0;
// Iterate over the string
while((n - i) >= (m - j)) {
// If the characters match
if(s[i] == p[j]) {
// Increment the index of the string and the pattern
i++;
j++;
}
// If the pattern is found
if(j == m) {
// Return true
return true;
}
// If the characters don't match
if(i < n && s[i] != p[j]) {
// If the index of the pattern is not 0
// Update the index of the pattern
if(j != 0) {
j = lps[j - 1];
// Update the index of the string
} else {
i++;
}
}
}
// If the pattern is not found
// Return false
return false;
}