-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.java
More file actions
43 lines (37 loc) · 1021 Bytes
/
Copy pathkmp.java
File metadata and controls
43 lines (37 loc) · 1021 Bytes
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
package templates;
import java.util.*;
import java.io.*;
public class kmp {
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public int[] prefixFunction(StringBuilder s){
int n=s.length();
int[] pi=new int[n];
for(int i=1;i<n;i++){
int j=pi[i-1];
while(j>0 && s.charAt(j)!=s.charAt(i)){
j=pi[j-1];
}
if(s.charAt(j)==s.charAt(i)){
j++;
}
pi[i]=j;
}
return pi;
}
public int match(StringBuilder pattern,StringBuilder text){
int ans=-1;
StringBuilder tot=new StringBuilder(pattern);
tot.append('#');
tot.append(text);
int n=pattern.length();
int[] pi=prefixFunction(tot);
for(int i=0;i<tot.length();i++){
if(pi[i]==n){
ans=i-(n+1)-n+1;
break;
}
}
return ans;
}
}