forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZAlgorithm.java
More file actions
48 lines (39 loc) · 1.06 KB
/
ZAlgorithm.java
File metadata and controls
48 lines (39 loc) · 1.06 KB
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
/*
* https://en.wikipedia.org/wiki/Z-algorithm
*/
package com.thealgorithms.strings;
public final class ZAlgorithm {
private ZAlgorithm() {
throw new UnsupportedOperationException("Utility class");
}
public static int[] zFunction(String s) {
int n = s.length();
int[] z = new int[n];
int l = 0;
int r = 0;
for (int i = 1; i < n; i++) {
if (i <= r) {
z[i] = Math.min(r - i + 1, z[i - l]);
}
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {
z[i]++;
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
public static int search(String text, String pattern) {
String s = pattern + "$" + text;
int[] z = zFunction(s);
int p = pattern.length();
for (int i = 0; i < z.length; i++) {
if (z[i] == p) {
return i - p - 1;
}
}
return -1;
}
}