forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Z_Algorithm.coffee
57 lines (40 loc) · 1.04 KB
/
Z_Algorithm.coffee
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
getZarr = (str, Z) ->
n = str.length
Left = 0
Right = 0
for i in [1...n]
if i > Right
Left = i
Right = i
while Right < n and str[Right - Left] is str[Right]
Right += 1
Z[i] = Right - Left
Right -= 1
else
k = i - Left
if Z[k] < Right - i + 1
Z[i] = Z[k]
else
Left = i
while Right < n and str[Right - Left] is str[Right]
Right += 1
Z[i] = Right - Left
Right -= 1
0 # Return 0
search = (text, pattern) ->
concat = pattern + "$" + text
size = concat.length
Z = Array(size).fill(0)
getZarr concat, Z
for i in [0...size]
if Z[i] is pattern.length
console.log "Pattern found at " + (i - pattern.length)
0 # Return 0
text = "namanchamanbomanamansanam"
pattern = "aman"
search text, pattern
### Output
Pattern found at 2
Pattern found at 8
Pattern found at 17
###