Skip to content

Commit 79a73ae

Browse files
authored
KMP algorithm
1 parent 85771ea commit 79a73ae

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Misc/KMP.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2+
/*
3+
Implementation of Knuth–Morris–Pratt algorithm
4+
Usage:
5+
final String T = "AAAAABAAABA";
6+
final String P = "AAAA";
7+
KMPmatcher(T, P);
8+
*/
9+
public class KMP {
10+
11+
// find the starting index in string T[] that matches the search word P[]
12+
public void KMPmatcher(final String T, final String P) {
13+
final int m = T.length();
14+
final int n = P.length();
15+
final int[] pi = computePrefixFunction(P);
16+
int q = 0;
17+
for (int i = 0; i < m; i++) {
18+
while (q > 0 && T.charAt(i) != P.charAt(q)) {
19+
q = pi[q - 1];
20+
}
21+
22+
if (T.charAt(i) == P.charAt(q)) {
23+
q++;
24+
}
25+
26+
if (q == n) {
27+
System.out.println("Pattern starts: " + (i + 1 - n));
28+
q = pi[q - 1];
29+
}
30+
}
31+
32+
}
33+
34+
// return the prefix function
35+
private int[] computePrefixFunction(final String P) {
36+
final int n = P.length();
37+
final int[] pi = new int[n];
38+
pi[0] = 0;
39+
int q = 0;
40+
for (int i = 1; i < n; i++) {
41+
while (q > 0 && P.charAt(q) != P.charAt(i)) {
42+
q = pi[q - 1];
43+
}
44+
45+
if (P.charAt(q) == P.charAt(i)) {
46+
q++;
47+
}
48+
49+
pi[i] = q;
50+
51+
}
52+
53+
return pi;
54+
}
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy