Skip to content

Commit d006404

Browse files
committed
KMP
1 parent b312567 commit d006404

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
public class KMP {
2+
3+
// Function to compute LPS array
4+
public static int[] computeLPSArray(String pattern) {
5+
int M = pattern.length();
6+
int[] lps = new int[M];
7+
int len = 0; // length of the previous longest prefix suffix
8+
int i = 1;
9+
lps[0] = 0; // lps[0] is always 0
10+
11+
while (i < M) {
12+
if (pattern.charAt(i) == pattern.charAt(len)) {
13+
len++;
14+
lps[i] = len;
15+
i++;
16+
} else {
17+
if (len != 0) {
18+
len = lps[len - 1];
19+
} else {
20+
lps[i] = 0;
21+
i++;
22+
}
23+
}
24+
}
25+
return lps;
26+
}
27+
28+
// KMP Search function
29+
public static void KMPSearch(String pattern, String text) {
30+
int M = pattern.length();
31+
int N = text.length();
32+
33+
int[] lps = computeLPSArray(pattern);
34+
int i = 0; // index for text
35+
int j = 0; // index for pattern
36+
37+
while (i < N) {
38+
if (pattern.charAt(j) == text.charAt(i)) {
39+
i++;
40+
j++;
41+
}
42+
43+
if (j == M) {
44+
System.out.println("Pattern found at index " + (i - j));
45+
j = lps[j - 1];
46+
} else if (i < N && pattern.charAt(j) != text.charAt(i)) {
47+
if (j != 0)
48+
j = lps[j - 1];
49+
else
50+
i++;
51+
}
52+
}
53+
}
54+
55+
public static void main(String[] args) {
56+
String text = "ABABDABACDABABCABAB";
57+
String pattern = "ABABCABAB";
58+
KMPSearch(pattern, text);
59+
}
60+
}

0 commit comments

Comments
 (0)