forked from saisarathganti/DataStructures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMPS.java
More file actions
52 lines (50 loc) · 985 Bytes
/
KMPS.java
File metadata and controls
52 lines (50 loc) · 985 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
44
45
46
47
48
49
50
51
52
import java.util.*;
public class KMPS {
public int[] subarray(char[] substring) {
int pre[] =new int[substring.length];
int j=0;
for(int i=1;i<substring.length;) {
if(substring[j]==substring[i]) {
pre[i]=j+1;
i++;
j++;
}
else {
if(j!=0)
j=pre[j-1];
else {
pre[i]=0;
i++;
}
}
}
return pre;
}
public boolean KMP(char[] substring,char[] string) {
int[] pre=subarray(substring);
int i=0,j=0;
while(i<string.length&&j<substring.length) {
if(string[i]==substring[j]) {
i++;j++;
}
else {
if(j!=0)
j=pre[j-1];
else
i++;
}
}
if(j==substring.length)
return true;
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
String string=s.next();
String substring=s.next();
KMPS ss=new KMPS();
boolean result=ss.KMP(string.toCharArray(),substring.toCharArray());
System.out.println(result);
}
}