forked from saisarathganti/DataStructures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZ.java
More file actions
68 lines (67 loc) · 1.48 KB
/
Z.java
File metadata and controls
68 lines (67 loc) · 1.48 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.*;
public class Z {
public int[] calculate(char[] total) {
int[] Z=new int[total.length];
int left=0,right=0;
for(int k=1;k<total.length;k++) {
if(k>right) {
left=right=k;
while(right<total.length&&total[right]==total[right-left]) {
right++;
}
Z[k]=right-left;
right--;
}
else {
int k1=k-left;
if(Z[k1]<right-k+1) {
Z[k]=Z[k1];
}
else {
left=k;
while(right<total.length&&total[right]==total[right-left]) {
right++;
}
Z[k]=right-left;
right--;
}
}
}
return Z;
}
public List<Integer> matchPattern(char[] string,char[] substring) {
char[] total=new char[string.length+1+substring.length];
int i=0;
for(char ch : substring) {
total[i]=ch;
i++;
}
total[i]='$';
i++;
for(char ch : string) {
total[i]=ch;
i++;
}
List<Integer> result=new ArrayList<>();
int Z[]=calculate(total);
for(int j=0;j<Z.length;j++) {
if(Z[j]==substring.length) {
result.add(j-substring.length-1);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
/*
String text = "aaabcxyzaaaabczaaczabbaaaaaabc";
String pattern = "aaabc";
ZAlgorithm zAlgorithm = new ZAlgorithm();
List<Integer> result = zAlgorithm.matchPattern(text.toCharArray(), pattern.toCharArray());
result.forEach(System.out::println);
*/
/////////////this type input is given
s.close();
}
}