Files
Java/src/main/java/com/thealgorithms/strings/KMP.java
Divyansh Saxena dfaa495639 Refactor KMP and RabinKarp: Improve Reusability and Test Coverage (#7250)
* first commit

* Running KMPTest and RabinKarpTest with fixed formatting

* now build failed error resolved

* now build failed error resolved 2

---------

Co-authored-by: Divyansh Saxena <divyanshsaxena@gmail.com>
Co-authored-by: Deniz Altunkapan <deniz.altunkapan@outlook.com>
2026-02-01 14:51:13 +00:00

68 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.thealgorithms.strings;
import java.util.ArrayList;
import java.util.List;
/**
* Implementation of KnuthMorrisPratt algorithm Usage: see the main function
* for an example
*/
public final class KMP {
private KMP() {
}
/**
* find the starting index in string haystack[] that matches the search word P[]
*
* @param haystack The text to be searched
* @param needle The pattern to be searched for
* @return A list of starting indices where the pattern is found
*/
public static List<Integer> kmpMatcher(final String haystack, final String needle) {
List<Integer> occurrences = new ArrayList<>();
if (haystack == null || needle == null || needle.isEmpty()) {
return occurrences;
}
final int m = haystack.length();
final int n = needle.length();
final int[] pi = computePrefixFunction(needle);
int q = 0;
for (int i = 0; i < m; i++) {
while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
q = pi[q - 1];
}
if (haystack.charAt(i) == needle.charAt(q)) {
q++;
}
if (q == n) {
occurrences.add(i + 1 - n);
q = pi[q - 1];
}
}
return occurrences;
}
// return the prefix function
private static int[] computePrefixFunction(final String p) {
final int n = p.length();
final int[] pi = new int[n];
pi[0] = 0;
int q = 0;
for (int i = 1; i < n; i++) {
while (q > 0 && p.charAt(q) != p.charAt(i)) {
q = pi[q - 1];
}
if (p.charAt(q) == p.charAt(i)) {
q++;
}
pi[i] = q;
}
return pi;
}
}