Skip to content

Commit bfc2181

Browse files
authored
Update KMP.cpp
1 parent 1198b1c commit bfc2181

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

KMP.cpp

+25-24
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
vector<int> prefix_function(string &s)
44
{
5-
int n = (int)s.length();
5+
int n = s.size();
66
vector<int> pi(n);
7-
for (int i = 1; i < n; i++)
7+
for(int i = 1; i < n; i++)
88
{
9-
int j = pi[i-1];
10-
while (j > 0 && s[i] != s[j])
11-
j = pi[j-1];
9+
int j = pi[i - 1];
10+
while(j > 0 && s[i] != s[j])
11+
j = pi[j - 1];
1212
if (s[i] == s[j])
1313
j++;
1414
pi[i] = j;
@@ -18,14 +18,14 @@ vector<int> prefix_function(string &s)
1818

1919
vector<int> find_occurences(string &text, string &pattern)
2020
{
21-
string cur=pattern + '#' + text;
22-
int sz1=text.size(), sz2=pattern.size();
21+
string cur = pattern + '#' + text;
22+
int sz1 = text.size(), sz2 = pattern.size();
2323
vector<int> v;
24-
vector<int> lps=prefix_function(cur);
25-
for(int i=sz2+1;i<=sz1+sz2;i++)
24+
vector<int> lps = prefix_function(cur);
25+
for(int i = sz2 + 1; i <= sz1 + sz2; i++)
2626
{
27-
if(lps[i]==sz2)
28-
v.push_back(i-2*sz2);
27+
if(lps[i] == sz2)
28+
v.push_back(i - 2 * sz2);
2929
}
3030
return v;
3131
}
@@ -34,14 +34,14 @@ vector<int> find_occurences(string &text, string &pattern)
3434

3535
vector<int> prefix_function(vector<int> &v)
3636
{
37-
int n = (int)v.size();
37+
int n = v.size();
3838
vector<int> pi(n);
39-
for (int i = 1; i < n; i++)
39+
for(int i = 1; i < n; i++)
4040
{
41-
int j = pi[i-1];
42-
while (j > 0 && v[i] != v[j])
43-
j = pi[j-1];
44-
if (v[i] == v[j])
41+
int j = pi[i - 1];
42+
while(j > 0 && v[i] != v[j])
43+
j = pi[j - 1];
44+
if(v[i] == v[j])
4545
j++;
4646
pi[i] = j;
4747
}
@@ -50,26 +50,27 @@ vector<int> prefix_function(vector<int> &v)
5050

5151
vector<int> find_occurences(vector<int> &text, vector<int> &pattern)
5252
{
53-
vector<int> v=pattern;
53+
vector<int> v = pattern;
5454
v.push_back(-1);
5555
for(auto &it:text)
5656
v.push_back(it);
57-
int sz1=text.size(), sz2=pattern.size();
58-
vector<int> lps=prefix_function(v);
57+
int sz1 = text.size(), sz2 = pattern.size();
58+
vector<int> lps = prefix_function(v);
5959
vector<int> store;
60-
for(int i=sz2+1;i<=sz1+sz2;i++)
60+
for(int i = sz2 + 1; i <= sz1 + sz2; i++)
6161
{
62-
if(lps[i]==sz2)
63-
store.push_back(i-sz*2);
62+
if(lps[i] == sz2)
63+
store.push_back(i - 2 * sz2);
6464
}
6565
return v;
6666
}
6767

68-
6968
//Problem 1 (Basic KMP): https://codeforces.com/contest/1016/problem/B
7069
//Solution 1: https://codeforces.com/contest/1016/submission/41167402
7170

7271
//Problem 2 and Solution (Cyclic Matching - Vectors): http://codeforces.com/gym/100502/submission/41562571
7372

7473
//Problem 3 (Ranking Pattern): https://qr.ae/TUG5h9
7574
//Solution 3: http://p.ip.fi/Hwpy
75+
76+
//Problem 4: (Period of String) https://www.spoj.com/problems/FINDSR/

0 commit comments

Comments
 (0)