File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments