forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Algorithm.cs
121 lines (94 loc) · 2.63 KB
/
Z_Algorithm.cs
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
Z Algorithm In C#
This algorithm finds all occurrences
of a pattern in a text in linear time.
*/
using System;
class PatternSearch
{
/*
This function prints all the occurences
of a pattern in a text using Z algorithm
*/
public static void search(string text, string pattern)
{
// Creation of Concatenated String
string concat = pattern + "$" + text;
int l = concat.Length;
// Construct a new temporary array
int[] temp = new int[l];
getTempArr(concat, temp);
/*
Iterate through temp array to
find the matching condition
*/
for (int i = 0; i < l; ++i)
{
/*
If matched region is equal to
pattern lentgh, pattern is found
*/
if (temp[i] == pattern.Length)
{
Console.WriteLine("Pattern occurs at index: " +
(i - pattern.Length - 1));
}
}
}
// Fills temporary array for given string str
private static void getTempArr(string str, int[] temp)
{
int n = str.Length;
int L = 0, R = 0;
for (int i = 1; i < n; ++i)
{
if (i > R)
{
L = R = i;
while (R < n && str[R - L] == str[R])
{
R++;
}
temp[i] = R - L;
R--;
}
else
{
int k = i - L;
if (temp[k] < R - i + 1)
{
temp[i] = temp[k];
}
else
{
L = i;
while (R < n && str[R - L] == str[R])
{
R++;
}
temp[i] = R - L;
R--;
}
}
}
}
public static void Main(string[] args)
{
Console.WriteLine("Enter the String value: ");
String text = Console.ReadLine();
Console.WriteLine("Enter the Pattern to search: ");
String pattern = Console.ReadLine();
Console.WriteLine();
search(text, pattern);
}
}
/**
Enter the String value: AABACAADAAABACHGGH
Enter the Pattern to search: AABA
Pattern occurs at index: 0
Pattern occurs at index: 9
---------------------------------------------------
Enter the String value: THIS IS A TEST CASE
Enter the Pattern to search: TEST
Pattern occurs at index: 10
*/