Skip to content

Commit 94fce46

Browse files
author
Mrinal Chauhan
committed
Z Algorithm
1 parent be0b1d5 commit 94fce46

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.thealgorithms.strings;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Class to implement the Z Algorithm for pattern matching in strings.
8+
* The Z Algorithm finds all occurrences of a pattern within a text.
9+
*/
10+
public final class Zalgorithm {
11+
private Zalgorithm() {
12+
}
13+
14+
/**
15+
* Calculates the Z array for a given string.
16+
*
17+
* @param s the input string
18+
* @return the Z array where Z[i] indicates the length of the longest substring
19+
* starting from s[i] that is also a prefix of s
20+
*/
21+
public static int[] calculateZ(String s) {
22+
int n = s.length();
23+
int[] Z = new int[n];
24+
int left = 0, right = 0;
25+
26+
for (int i = 1; i < n; i++) {
27+
if (i <= right) {
28+
Z[i] = Math.min(right - i + 1, Z[i - left]);
29+
}
30+
while (i + Z[i] < n && s.charAt(Z[i]) == s.charAt(i + Z[i])) {
31+
Z[i]++;
32+
}
33+
if (i + Z[i] - 1 > right) {
34+
left = i;
35+
right = i + Z[i] - 1;
36+
}
37+
}
38+
return Z;
39+
}
40+
41+
/**
42+
* Finds all occurrences of a pattern in the text using the Z Algorithm.
43+
*
44+
* @param text the text in which to search for the pattern
45+
* @param pattern the pattern to search for
46+
* @return a list of starting indices of occurrences of the pattern in the text
47+
*/
48+
public static List<Integer> findPatternOccurrences(String text, String pattern) {
49+
String combined = pattern + "$" + text;
50+
int[] Z = calculateZ(combined);
51+
List<Integer> occurrences = new ArrayList<>();
52+
int patternLength = pattern.length();
53+
54+
for (int i = 0; i < Z.length; i++) {
55+
if (Z[i] == patternLength) {
56+
occurrences.add(i - patternLength - 1);
57+
}
58+
}
59+
return occurrences;
60+
}
61+
}

0 commit comments

Comments
 (0)