-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay90.java
More file actions
43 lines (39 loc) · 1.25 KB
/
Day90.java
File metadata and controls
43 lines (39 loc) · 1.25 KB
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
35
36
37
38
39
40
41
42
import java.util.ArrayList;
import java.util.List;
public class Day90 {
public static List<Integer> findOccurrences(String text, String pattern) {
List<Integer> occurrences = new ArrayList<>();
int n = text.length();
int m = pattern.length();
int[] prefix = new int[m];
int j = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern.charAt(i) != pattern.charAt(j)) {
j = prefix[j - 1];
}
if (pattern.charAt(i) == pattern.charAt(j)) {
prefix[i] = ++j;
}
}
j = 0;
for (int i = 0; i < n; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
j = prefix[j - 1];
}
if (text.charAt(i) == pattern.charAt(j)) {
j++;
}
if (j == m) {
occurrences.add(i - m + 2);
j = prefix[j - 1];
}
}
return occurrences;
}
public static void main(String[] args) {
String text = "cxyzghxyzvjkxyz";
String pattern = "xyz";
List<Integer> occurrences = findOccurrences(text, pattern);
System.out.println("Occurrences = " + occurrences);
}
}