Skip to content

Commit 00d2e57

Browse files
authored
Create palindrome-partitioning-iv.py
1 parent afa0a05 commit 00d2e57

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Python/palindrome-partitioning-iv.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def checkPartitioning(self, s):
6+
"""
7+
:type s: str
8+
:rtype: bool
9+
"""
10+
def modified_manacher(s):
11+
s = '^#' + '#'.join(s) + '#$'
12+
P = [0]*len(s)
13+
dp1 = [False]*len(s) # dp1[i]: s[:i] is a palindromic string
14+
dp2 = [False]*len(s) # dp2[i]: s[:i+1] is composed of 2 palindromic strings
15+
C, R = 0, 0
16+
for i in xrange(1, len(s)-1):
17+
i_mirror = 2*C-i
18+
if R > i:
19+
P[i] = min(R-i, P[i_mirror])
20+
while s[i+1+P[i]] == s[i-1-P[i]]:
21+
if dp1[i-1-P[i]]:
22+
dp2[i+1+P[i]] = True
23+
P[i] += 1
24+
if i+1+P[i] == len(s)-1 and dp2[i-1-P[i]]:
25+
return True
26+
if i-1-P[i] == 0:
27+
dp1[i+1+P[i]] = True
28+
if i+P[i] > R:
29+
C, R = i, i+P[i]
30+
return False
31+
32+
return modified_manacher(s)
33+
34+
35+
# Time: O(n^2)
36+
# Space: O(n)
37+
class Solution(object):
38+
def checkPartitioning(self, s):
39+
"""
40+
:type s: str
41+
:rtype: bool
42+
"""
43+
dp = [[False]*len(s) for _ in xrange(len(s))]
44+
for i in reversed(xrange(len(s))):
45+
for j in xrange(i, len(s)):
46+
if s[i] == s[j] and (j-i < 2 or dp[i+1][j-1]):
47+
dp[i][j] = True
48+
for i in xrange(1, len(s)):
49+
for j in xrange(i+1, len(s)):
50+
if dp[0][i-1] and dp[i][j-1] and dp[j][-1]:
51+
return True
52+
return False

0 commit comments

Comments
 (0)