forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Algorithm.py
61 lines (45 loc) · 1.09 KB
/
Z_Algorithm.py
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
def getZarr(str, Z):
n = len(str)
Left = 0
Right = 0
for i in range(1, n):
if i > Right:
Left = i
Right = i
while Right < n and str[Right - Left] == 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] == str[Right]:
Right += 1
Z[i] = Right - Left
Right -= 1
def search(text, pattern):
concat = pattern + "$" + text
size = len(concat)
Z = [0] * size
getZarr(concat, Z)
for i in range(0, size):
if Z[i] == len(pattern):
print("Pattern found at " + str(i - len(pattern)))
def main():
text = input()
pattern = input()
search(text, pattern)
if __name__ == '__main__':
main()
'''
Input:
namanchamanbomanamansanam
aman
Output:
Pattern found at 2
Pattern found at 8
Pattern found at 17
'''