-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZFunction.java
More file actions
34 lines (30 loc) · 828 Bytes
/
ZFunction.java
File metadata and controls
34 lines (30 loc) · 828 Bytes
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
package string.zFunction;
public class ZFunction {
public int[] z(String s) {
int n = s.length();
int[] z = new int[n];
for (int i = 1, l = 0, r = 0; 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 int[] z_trivial(String s) {
int n = s.length();
int[] z = new int[n];
for (int i = 0; i < n; i++) {
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {
z[i]++;
}
}
return z;
}
}