forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Algorithm.java
74 lines (58 loc) · 1.51 KB
/
Z_Algorithm.java
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
69
70
71
72
73
74
import java.util.*;
public class Z_Algorithm {
static void getZarr(String str, int Z[]){
int n = str.length(), Left = 0, Right = 0, k;
for(int i = 1; i < n; i++)
{
if(i > Right)
{
Left = Right = i;
while(Right < n && str.charAt(Right - Left) == str.charAt(Right))
Right++;
Z[i] = Right - Left;
Right--;
}
else
{
k = i - Left;
if(Z[k] < Right - i + 1)
Z[i] = Z[k];
else
{
Left = i;
while(Right < n && str.charAt(Right - Left) == str.charAt(Right))
Right++;
Z[i] = Right - Left;
Right--;
}
}
}
}
static void search(String text, String pattern) {
String concat = pattern + "$" + text;
int size = concat.length();
int Z[] = new int[size];
getZarr(concat, Z);
for (int i = 0; i < size; i++) {
if (Z[i] == pattern.length()) {
int index = i - pattern.length();
System.out.println("Pattern found at " + index);
}
}
}
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
String pattern = sc.nextLine();
search(text, pattern);
}
}
/*
Sample Input:
namanchamanbomanamansanam (text)
aman (pattern)
Sample Output:
Pattern found at 2
Pattern found at 8
Pattern found at 17
*/