Skip to content

Commit 0b53753

Browse files
authored
Merge pull request #335 from durid17/Z-Algorithm
Z_Algorithm
2 parents f13b476 + bee1ee7 commit 0b53753

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Z_Algorithm():
2+
"""
3+
return all occurences of string s in text, returns its indexes starting from zero
4+
delimeter should be charachter which will not occur neither is S nor in text
5+
by default its '$'
6+
"""
7+
@staticmethod
8+
def find_occurrences(s:str , text:str , delimeter = '$'):
9+
return Z_Algorithm.z_function(s + delimeter + text , len(s))
10+
11+
@staticmethod
12+
def z_function(text:str , size:int):
13+
l = 0
14+
r = 0
15+
z = [0] * len(text)
16+
for i in range(1 , len(text)):
17+
if i <= r:
18+
z[i] = min(r - i + 1 , z[i - l])
19+
while i + z[i] < len(text) and text[z[i]] == text[i + z[i]]:
20+
z[i] += 1
21+
22+
if i + z[i] - 1 > r:
23+
l = i
24+
r = i + z[i] - 1
25+
26+
res = []
27+
for i in range(size , len(text)):
28+
if z[i] == size:
29+
res.append(i - size - 1)
30+
return res

0 commit comments

Comments
 (0)