-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.java
More file actions
113 lines (96 loc) · 2.58 KB
/
KMP.java
File metadata and controls
113 lines (96 loc) · 2.58 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madhavadabare
*/
public class KMP {
static int[] prefixFn(String pattern) {
String P[] = pattern.split("");
int pi[] = new int[P.length];
int k = 0;
pi[0] = k;
for (int q = 1; q < pi.length; q++) {
while (k > 0 && !P[k].equals(P[q])) {
k = pi[k];
}
if (P[k].equals(P[q])) {
k++;
}
pi[q] = k;
}
return pi;
}
static int[] prefixFn(char[] pattern) {
int pi[] = new int[pattern.length];
int k = 0;
pi[0] = k;
for (int q = 1; q < pi.length; q++) {
while (k > 0 && pattern[k] != pattern[q]) {
k = pi[k];
}
if (pattern[k] == pattern[q]) {
k++;
}
pi[q] = k;
}
return pi;
}
static String KMP(String text, String pattern) {
String result = "";
int pi[] = prefixFn(pattern);
String[] P = pattern.split(""), T = text.split("");
int q = 0;
for (int i = 0; i < T.length; i++) {
while (q > 0 && !P[q].equals(T[i])) {
q = pi[q];
}
if (P[q].equals(T[i])) {
q++;
}
if (q == P.length) {
result += i - P.length + 1 + " ";
q = pi[q - 1];
}
}
return result;
}
static int[] preProcessPattern(char[] ptrn) {
int i = 0, j = -1;
int ptrnLen = ptrn.length;
int[] b = new int[ptrnLen + 1];
b[i] = j;
while (i < ptrnLen) {
while (j >= 0 && ptrn[i] != ptrn[j]) {
j = b[j];
}
i++;
j++;
b[i] = j;
}
return b;
}
static String searchSubString(String T, String P) {
String result = "";
char[] text = T.toCharArray(), ptrn = P.toCharArray();
int i = 0, j = 0;
int ptrnLen = ptrn.length;
int txtLen = text.length;
int[] b = preProcessPattern(ptrn);
while (i < txtLen) {
while (j >= 0 && text[i] != ptrn[j]) {
j = b[j];
}
i++;
j++;
if (j == ptrnLen) {
result += i - ptrnLen + " ";
j = b[j];
}
}
return result;
}
}