Skip to content

Commit 8bb54ca

Browse files
authored
Merge pull request #1362 from vakhokoto/z-function
z function added
2 parents b8fa504 + a983a15 commit 8bb54ca

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Strings/ZFunction.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Initialisation of strings algorithm Z function
2+
// detailed review and proper examples can be seen on the link bewlow
3+
//
4+
// Link of algorithm review: https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/
5+
package Strings;
6+
7+
public class ZFunction {
8+
private String string;
9+
10+
public ZFunction(String string){
11+
this.string = string;
12+
}
13+
14+
public int[] getArray(){
15+
int length = string.length();
16+
int[] z = new int[length];
17+
int l = 0, r = 0;
18+
for (int i=0; i<length; i++){
19+
if (i > l && i <= r){
20+
z[i] = Math.min(z[i - l], r - i + 1);
21+
}
22+
while (i + z[i] < length && string.charAt(z[i]) == string.charAt(i + z[i])){
23+
z[i]++;
24+
}
25+
if (i + z[i] > r){
26+
l = i;
27+
r = i + z[i] - 1;
28+
}
29+
}
30+
31+
return z;
32+
}
33+
}

0 commit comments

Comments
 (0)