-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathminCut.go
More file actions
42 lines (36 loc) · 906 Bytes
/
Copy pathminCut.go
File metadata and controls
42 lines (36 loc) · 906 Bytes
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
/* https://leetcode.com/problems/palindrome-partitioning-ii/
Given a string s, partition s such that every substring of
the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
*/
package ldp
func minCut(s string) int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
length := len(s)
dp := make([][]bool, length) // i~j是否回文
resDp := make([]int, length, length)
for i := 0; i < length; i++ {
resDp[i] = i
dp[i] = make([]bool, length)
for j := 0; j <= i; j++ {
if s[i] == s[j] && (i-j < 2 || dp[j+1][i-1]) {
dp[j][i] = true
if j == 0 { // 0~i为回文,不需要分割
resDp[i] = 0
} else {
resDp[i] = min(resDp[i], resDp[j-1]+1)
}
}
}
}
return resDp[length-1]
}