-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKMPSubString.java
More file actions
62 lines (56 loc) · 1.04 KB
/
KMPSubString.java
File metadata and controls
62 lines (56 loc) · 1.04 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
public class KMPSubString {
public int[] computeArray(String pattern) {
int [] arr=new int[pattern.length()];
int index =0;
for(int i=1;i<pattern.length();) {
if(pattern.charAt(i)==pattern.charAt(index)) {
arr[i]=index+1;
index++;
i++;
}
else {
if(index!=0) {
index=arr[index-1];
}
else {
arr[i]=0;
i++;
}
}
}
return arr;
}
public boolean KMP(String text,String pattern) {
int[] arr=computeArray(pattern);
int i=0;
int j=0;
while(i<text.length()&&j<pattern.length()) {
if(text.charAt(i)==pattern.charAt(j)) {
i++;
j++;
}
else {
if(j!=0) {
j=arr[j-1];
}
else {
i++;
}
}
}
if(j==pattern.length()) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abxabcabcaby";
String pattern = "abcxy";
KMPSubString ob=new KMPSubString();
boolean result=ob.KMP(str,pattern);
System.out.println(result);
}
}