forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kmp.java
67 lines (58 loc) · 1.96 KB
/
Kmp.java
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
package strings;
import java.util.Random;
// https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm
public class Kmp {
public static int[] prefixFunction(String s) {
int[] p = new int[s.length()];
int k = 0;
for (int i = 1; i < s.length(); i++) {
while (k > 0 && s.charAt(k) != s.charAt(i)) k = p[k - 1];
if (s.charAt(k) == s.charAt(i))
++k;
p[i] = k;
}
return p;
}
public static int findSubstring(String haystack, String needle) {
int m = needle.length();
if (m == 0)
return 0;
int[] p = prefixFunction(needle);
for (int i = 0, k = 0; i < haystack.length(); i++) {
while (k > 0 && needle.charAt(k) != haystack.charAt(i)) k = p[k - 1];
if (needle.charAt(k) == haystack.charAt(i))
++k;
if (k == m)
return i + 1 - m;
}
return -1;
}
public static int minPeriod(String s) {
int n = s.length();
int[] p = prefixFunction(s);
int maxBorder = p[n - 1];
int minPeriod = n - maxBorder;
// check periodicity
// if (n % minPeriod != 0) return -1;
return minPeriod;
}
// random tests
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 10_000; step++) {
String s = getRandomString(rnd, 100);
String pattern = getRandomString(rnd, 5);
int pos1 = findSubstring(s, pattern);
int pos2 = s.indexOf(pattern);
if (pos1 != pos2)
throw new RuntimeException();
}
System.out.println(minPeriod("abababab"));
}
static String getRandomString(Random rnd, int maxlen) {
int n = rnd.nextInt(maxlen);
char[] s = new char[n];
for (int i = 0; i < n; i++) s[i] = (char) ('a' + rnd.nextInt(3));
return new String(s);
}
}