-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathKMPFunction.java
More file actions
82 lines (82 loc) · 1.55 KB
/
KMPFunction.java
File metadata and controls
82 lines (82 loc) · 1.55 KB
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
import java.math.*;
import java.io.*;
import java.util.*;
class KMPFunction
{
StringTokenizer st;
BufferedReader in;
PrintWriter ob;
public static void main(String args[])throws IOException {
new KMPFunction().run();
}
void run()throws IOException {
//in=new BufferedReader(new FileReader("input.txt"));
//ob=new PrintWriter("output.txt");
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(System.out);
solve();
ob.flush();
}
void solve()throws IOException {
read();
char s[]=ns().toCharArray();
int l=s.length;
int f[]=new int[l]; // sandip's built kmp function
int index=0;
f[0]=0;
for(int i=0;i<l;){
if(s[i]==s[index]){
f[i]=index+1;
index+=1;
i++;
}
else{
if(index!=0){
index=f[index-1];
}
else
{
f[i]=0;
i++;
}
}
}
for(int i=0;i<l;i++)
ob.print(f[i]+" ");
ob.println();
}
void read()throws IOException {
st=new StringTokenizer(in.readLine());
}
int ni(){
return Integer.parseInt(st.nextToken());
}
long nl(){
return Long.parseLong(st.nextToken());
}
double nd(){
return Double.parseDouble(st.nextToken());
}
String ns(){
return st.nextToken();
}
char nc(){
return st.nextToken().charAt(0);
}
int[] nia(int n)throws IOException {
int a[]=new int[n];
read();
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(st.nextToken());
}
return a;
}
long[] nla(int n)throws IOException {
long a[]=new long[n];
read();
for(int i=0;i<n;i++){
a[i]=Long.parseLong(st.nextToken());
}
return a;
}
}