Skip to content

Commit 2ef2124

Browse files
authored
Update maximum-product-of-the-length-of-two-palindromic-substrings.py
1 parent 37f7623 commit 2ef2124

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Python/maximum-product-of-the-length-of-two-palindromic-substrings.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,51 @@
11
# Time: O(n)
22
# Space: O(n)
33

4+
import collections
5+
6+
47
class Solution(object):
8+
def maxProduct(self, s):
9+
"""
10+
:type s: str
11+
:rtype: int
12+
"""
13+
def manacher(s):
14+
s = '^#' + '#'.join(s) + '#$'
15+
P = [0]*len(s)
16+
C, R = 0, 0
17+
for i in xrange(1, len(s)-1):
18+
i_mirror = 2*C-i
19+
if R > i:
20+
P[i] = min(R-i, P[i_mirror])
21+
while s[i+1+P[i]] == s[i-1-P[i]]:
22+
P[i] += 1
23+
if i+P[i] > R:
24+
C, R = i, i+P[i]
25+
return P
26+
27+
P = manacher(s)
28+
q = collections.deque()
29+
left = [0]
30+
for i in xrange(len(s)):
31+
while q and q[0][1] < i:
32+
q.popleft()
33+
left.append(max(left[-1], 1+2*(i-q[0][0]) if q else 1))
34+
q.append((i, i+P[2*i+2]//2))
35+
q = collections.deque()
36+
result = right = 0
37+
for i in reversed(xrange(len(s))):
38+
while q and q[0][1] > i:
39+
q.popleft()
40+
right = max(right, 1+2*(q[0][0]-i) if q else 1)
41+
q.append((i, i-P[2*i+2]//2))
42+
result = max(result, left[i]*right)
43+
return result
44+
45+
46+
# Time: O(n)
47+
# Space: O(n)
48+
class Solution2(object):
549
def maxProduct(self, s):
650
"""
751
:type s: str

0 commit comments

Comments
 (0)