5
5
class Solution (object ):
6
6
"""
7
7
Dynamic Programming:
8
- cuts[i]: minimum cuts needed for a palindrome partitioning of s[i:]
9
- is_palindrome[i][j]: whether s[i:i+1] is palindrome
8
+ cuts[i]: minimum cuts needed for a palindrome partitioning of s[i:], so we want cuts[0].
9
+
10
+ To get cuts[i-1], we scan j from i-1 to len(s)-1.
11
+ Once we comes to a is_palindrome[i-1][j]==true:
12
+ if j==len(s)-1, the string s[i-1:] is a Pal, cuts[i-1] is 0;
13
+ else: the current cut num (first cut s[i-1:j+1] and then cut the rest
14
+ s[j+1:]) is 1+cuts[j+1], compare it to the exisiting cuts[i-1], repalce if smaller.
15
+
16
+ is_palindrome[i][j]: whether s[i:j+1] is palindrome.
17
+ Here we need not to compute the is_palindrome in advance.
18
+ We use "Dynamic Programming" too, the formula is very intuitive:
19
+ is_palindrome[i][j] = true if (is_palindrome[i+1][j-1] and s[i] == s[j]) else false
20
+
21
+ A better O(n) space solution can be found here:
22
+ https://discuss.leetcode.com/topic/2840/my-solution-does-not-need-a-table-for-palindrome-is-it-right-it-uses-only-o-n-space
10
23
"""
24
+
11
25
def minCut (self , s ):
12
26
if not s :
13
27
return 0
@@ -16,28 +30,27 @@ def minCut(self, s):
16
30
is_palindrome = [[False for i in range (s_len )]
17
31
for j in range (s_len )]
18
32
19
- cuts = [s_len - 1 - i for i in range (s_len )]
20
- for i in range (s_len - 1 , - 1 , - 1 ):
33
+ cuts = [s_len - 1 - i for i in range (s_len )]
34
+ for i in range (s_len - 1 , - 1 , - 1 ):
21
35
for j in range (i , s_len ):
22
36
# if self.is_palindrome(i, j):
23
- if ((j - i < 2 and s [i ] == s [j ]) or
24
- (s [i ] == s [j ] and is_palindrome [i + 1 ][j - 1 ])):
37
+ if ((j - i < 2 and s [i ] == s [j ]) or (s [i ] == s [j ] and is_palindrome [i + 1 ][j - 1 ])):
25
38
is_palindrome [i ][j ] = True
26
39
if j == s_len - 1 :
27
40
cuts [i ] = 0
28
41
else :
29
- cuts [i ] = min (cuts [i ], 1 + cuts [j + 1 ])
42
+ cuts [i ] = min (cuts [i ], 1 + cuts [j + 1 ])
30
43
else :
31
44
pass
32
45
33
46
return cuts [0 ]
34
47
48
+
35
49
"""
36
- if __name__ == "__main__":
37
- sol = Solution()
38
- print sol.minCut("aab")
39
- print sol.minCut("aabb")
40
- print sol.minCut("aabaa")
41
- print sol.minCut("acbca")
42
- print sol.minCut("acbbca")
50
+ ""
51
+ "aab"
52
+ "aabb"
53
+ "aabaa"
54
+ "acbca"
55
+ "acbbca"
43
56
"""
0 commit comments