-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path686. Repeated String Match
More file actions
50 lines (39 loc) · 1.34 KB
/
686. Repeated String Match
File metadata and controls
50 lines (39 loc) · 1.34 KB
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
class Solution:
def repeatedStringMatch(self, A: 'str', B: 'str') -> 'int':
times = -(-len(B) // len(A)) # Equal to ceil(len(B) / len(A))
for i in range(2):
if B in A*(times+i):
return times+i
return -1
"""
# Rolling Hash Method
class Solution(object):
def repeatedStringMatch(self, A, B):
def check(index):
return all(A[(i + index) % len(A)] == x
for i, x in enumerate(B))
q = (len(B) - 1) // len(A) + 1
p, MOD = 113, 10**9 + 7
p_inv = pow(p, MOD-2, MOD)
power = 1
b_hash = 0
for x in map(ord, B):
b_hash += power * x
b_hash %= MOD
power = (power * p) % MOD
a_hash = 0
power = 1
for i in xrange(len(B)):
a_hash += power * ord(A[i % len(A)])
a_hash %= MOD
power = (power * p) % MOD
if a_hash == b_hash and check(0): return q
power = (power * p_inv) % MOD
for i in xrange(len(B), (q+1) * len(A)):
a_hash = (a_hash - ord(A[(i - len(B)) % len(A)])) * p_inv
a_hash += power * ord(A[i % len(A)])
a_hash %= MOD
if a_hash == b_hash and check(i - len(B) + 1):
return q if i < q * len(A) else q+1
return -1
"""