Skip to content

Commit 8812168

Browse files
authored
Create find-substring-with-given-hash-value.py
1 parent e00e506 commit 8812168

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# rolling hash
5+
class Solution(object):
6+
def subStrHash(self, s, power, modulo, k, hashValue):
7+
"""
8+
:type s: str
9+
:type power: int
10+
:type modulo: int
11+
:type k: int
12+
:type hashValue: int
13+
:rtype: str
14+
"""
15+
h, idx = 0, -1
16+
pw = pow(power, k-1, modulo)
17+
for i in reversed(xrange(len(s))):
18+
if i+k < len(s):
19+
h = (h-(ord(s[i+k])-ord('a')+1)*pw)%modulo
20+
h = (h*power+(ord(s[i])-ord('a')+1))%modulo
21+
if h == hashValue:
22+
idx = i
23+
return s[idx:idx+k]

0 commit comments

Comments
 (0)