forked from akhiluanandh/utility-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.cpp
63 lines (57 loc) · 829 Bytes
/
kmp.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
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
void getTable(string s,int* table)
{
int len = s.size();
table[0] = 0;
for(int i=1;i<len;)
{
while(s[i]!=s[0] && i<len)
{
table[i]=0;
i++;
}
if(i<len)
{
table[i]=1;
i++;
int matched=1;
while(s[matched]==s[i] && i<len)
{
matched++;
table[i] = matched;
i++;
}
}
}
}
int main()
{
string text,pattern;
cin>>pattern;
cin>>text;
int len = pattern.size();
int table[len];
getTable(pattern,table);
for(int i=0;i<text.size();i++)
{
int j=0;
int start = i;
while(pattern[j]==text[i] && i<text.size() && j<len)
{
i++;j++;
}
if(j==len)
{
printf("%d\n",start);
}
i = start;
if(j>=1)
{
i+=(j-table[j-1])-1;
}
}
return 0;
}