Skip to content

Commit b7c4cea

Browse files
authored
Create palindrome-partitioning-iii.py
1 parent f07cf5b commit b7c4cea

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Python/palindrome-partitioning-iii.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(k * n^2)
2+
# Space: O(n^2)
3+
4+
class Solution(object):
5+
def palindromePartition(self, s, k):
6+
"""
7+
:type s: str
8+
:type k: int
9+
:rtype: int
10+
"""
11+
# dp1[i][j]: minimum number of changes to make s[i, j] palindrome
12+
dp1 = [[0]*len(s) for _ in xrange(len(s))]
13+
for l in xrange(1, len(s)+1):
14+
for i in xrange(len(s)-l+1):
15+
j = i+l-1
16+
if i == j-1:
17+
dp1[i][j] = 0 if s[i] == s[j] else 1
18+
elif i != j:
19+
dp1[i][j] = dp1[i+1][j-1] if s[i] == s[j] else dp1[i+1][j-1]+1
20+
21+
# dp2[d][i]: minimum number of changes to divide s[0, i] into d palindromes
22+
dp2 = [[float("inf")]*len(s) for _ in xrange(2)]
23+
dp2[1] = dp1[0][:]
24+
for d in xrange(2, k+1):
25+
dp2[d%2] = [float("inf")]*len(s)
26+
for i in xrange(d-1, len(s)):
27+
for j in xrange(d-2, i):
28+
dp2[d%2][i] = min(dp2[d%2][i], dp2[(d-1)%2][j]+dp1[j+1][i])
29+
return dp2[k%2][len(s)-1]

0 commit comments

Comments
 (0)