From 07356b25ed0f8de035dbdef25a5f2118fcac44c2 Mon Sep 17 00:00:00 2001 From: Samat Tolebay <55315928+ordaboy@users.noreply.github.com> Date: Sun, 4 Oct 2020 00:21:36 +0500 Subject: [PATCH] Create Java - KMPAlgorithm.java --- Java - KMPAlgorithm.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Java - KMPAlgorithm.java diff --git a/Java - KMPAlgorithm.java b/Java - KMPAlgorithm.java new file mode 100644 index 0000000..4b59011 --- /dev/null +++ b/Java - KMPAlgorithm.java @@ -0,0 +1,34 @@ +public static int[] prefixFunction(String str) { + int[] prefixFunc = new int[str.length()]; + for (int i = 1; i < str.length(); i++) { + int j = prefixFunc[i - 1]; + + while (j > 0 && str.charAt(i) != str.charAt(j)) { + j = prefixFunc[j - 1]; + } + if (str.charAt(i) == str.charAt(j)) { + j += 1; + } + prefixFunc[i] = j; + } + return prefixFunc; +} + +public static List KMPSearch(String text, String pattern) { + int[] prefixFunc = prefixFunction(pattern); + ArrayList occurrences = new ArrayList(); + int j = 0; + for (int i = 0; i < text.length(); i++) { + while (j > 0 && text.charAt(i) != pattern.charAt(j)) { + j = prefixFunc[j - 1]; + } + if (text.charAt(i) == pattern.charAt(j)) { + j += 1; + } + if (j == pattern.length()) { + occurrences.add(i - j + 1); + j = prefixFunc[j - 1]; + } + } + return occurrences; +}