File tree Expand file tree Collapse file tree 2 files changed +21
-10
lines changed
main/java/com/thealgorithms/strings
test/java/com/thealgorithms/strings Expand file tree Collapse file tree 2 files changed +21
-10
lines changed Original file line number Diff line number Diff line change 11/*
22 * https://en.wikipedia.org/wiki/Z-algorithm
33 */
4-
54package com .thealgorithms .strings ;
65
7- public class ZAlgorithm {
6+ public final class ZAlgorithm {
7+
8+ private ZAlgorithm () {
9+ throw new UnsupportedOperationException ("Utility class" );
10+ }
811
912 public static int [] zFunction (String s ) {
1013 int n = s .length ();
1114 int [] z = new int [n ];
12- int l = 0 , r = 0 ;
15+ int l = 0 ;
16+ int r = 0 ;
17+
1318 for (int i = 1 ; i < n ; i ++) {
14- if (i <= r )
19+ if (i <= r ) {
1520 z [i ] = Math .min (r - i + 1 , z [i - l ]);
16- while (i + z [i ] < n && s .charAt (z [i ]) == s .charAt (i + z [i ]))
21+ }
22+
23+ while (i + z [i ] < n && s .charAt (z [i ]) == s .charAt (i + z [i ])) {
1724 z [i ]++;
25+ }
26+
1827 if (i + z [i ] - 1 > r ) {
1928 l = i ;
2029 r = i + z [i ] - 1 ;
2130 }
2231 }
32+
2333 return z ;
2434 }
2535
2636 public static int search (String text , String pattern ) {
2737 String s = pattern + "$" + text ;
2838 int [] z = zFunction (s );
2939 int p = pattern .length ();
40+
3041 for (int i = 0 ; i < z .length ; i ++) {
31- if (z [i ] == p )
42+ if (z [i ] == p ) {
3243 return i - p - 1 ;
44+ }
3345 }
3446 return -1 ;
3547 }
Original file line number Diff line number Diff line change 1- /*
2- * https://en.wikipedia.org/wiki/Z-algorithm
3- */
41package com .thealgorithms .strings ;
52
6- import static org .junit .jupiter .api .Assertions .*;
3+ import static org .junit .jupiter .api .Assertions .assertArrayEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertEquals ;
5+
76import org .junit .jupiter .api .Test ;
87
98public class ZAlgorithmTest {
You can’t perform that action at this time.
0 commit comments