-
Notifications
You must be signed in to change notification settings - Fork 8
/
rabin_karp.py
executable file
·47 lines (34 loc) · 922 Bytes
/
rabin_karp.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
class RollingHash:
def __init__(self, string, size):
self.str = string
self.hash = 0
for i in xrange(0, size):
self.hash += ord(self.str[i])
self.init = 0
self.end = size
def update(self):
if self.end <= len(self.str) -1:
self.hash -= ord(self.str[self.init])
self.hash += ord(self.str[self.end])
self.init += 1
self.end += 1
def digest(self):
return self.hash
def text(self):
return self.str[self.init:self.end]
def rabin_karp(substring, string):
if substring == None or string == None:
return -1
if substring == "" or string == "":
return -1
if len(substring) > len(string):
return -1
hs = RollingHash(string, len(substring))
hsub = RollingHash(substring, len(substring))
hsub.update()
for i in range(len(string)-len(substring)+1):
if hs.digest() == hsub.digest():
if hs.text() == substring:
return i
hs.update()
return -1