File tree Expand file tree Collapse file tree 3 files changed +82
-9
lines changed
leetcode/101-200/0132.Palindrome-Partitioning-II Expand file tree Collapse file tree 3 files changed +82
-9
lines changed Original file line number Diff line number Diff line change 1+ # [ 132.Palindrome Partitioning II] [ title ]
2+
3+ ## Description
4+ Given a string ` s ` , partition ` s ` such that every ` substring ` of the partition is a ` palindrome ` .
5+
6+ Return the ** minimum** cuts needed for a palindrome partitioning of ` s ` .
7+
8+ ** Example 1:**
9+
10+ ```
11+ Input: s = "aab"
12+ Output: 1
13+ Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
14+ ```
15+
16+ ** Example 2:**
17+
18+ ```
19+ Input: s = "a"
20+ Output: 0
21+ ```
22+
23+ ** Example 3:**
24+
25+ ```
26+ Input: s = "ab"
27+ Output: 1
28+ ```
29+
30+ ## 结语
31+
32+ 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[ awesome-golang-algorithm] [ me ]
33+
34+ [ title ] : https://leetcode.com/problems/palindrome-partitioning-ii/
35+ [ me ] : https://github.com/kylesliu/awesome-golang-algorithm
Original file line number Diff line number Diff line change 11package Solution
22
3- func Solution (x bool ) bool {
4- return x
3+ func Solution (s string ) int {
4+ cache := map [string ]int {}
5+ var (
6+ dfs func (string ) int
7+ isPalindrome func (string ) bool
8+ )
9+ isPalindrome = func (s string ) bool {
10+ l , r := 0 , len (s )- 1
11+ for ; l < r ; l , r = l + 1 , r - 1 {
12+ if s [l ] != s [r ] {
13+ return false
14+ }
15+ }
16+ return true
17+ }
18+ dfs = func (cur string ) int {
19+ l := len (cur )
20+ if l == 0 || l == 1 {
21+ return 0
22+ }
23+ if v , ok := cache [cur ]; ok {
24+ return v
25+ }
26+ if isPalindrome (cur ) {
27+ cache [cur ] = 0
28+ return 0
29+ }
30+ m := - 1
31+ for end := 1 ; end < len (cur ); end ++ {
32+ if isPalindrome (cur [:end ]) {
33+ r := dfs (cur [end :]) + 1
34+ if m == - 1 || m > r {
35+ m = r
36+ }
37+ }
38+ }
39+ cache [cur ] = m
40+ return m
41+ }
42+ return dfs (s )
543}
Original file line number Diff line number Diff line change @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
1010 // 测试用例
1111 cases := []struct {
1212 name string
13- inputs bool
14- expect bool
13+ inputs string
14+ expect int
1515 }{
16- {"TestCase " , true , true },
17- {"TestCase " , true , true },
18- {"TestCase " , false , false },
16+ {"TestCase1 " , "aab" , 1 },
17+ {"TestCase2 " , "a" , 0 },
18+ {"TestCase3 " , "ab" , 1 },
1919 }
2020
2121 // 开始测试
@@ -30,10 +30,10 @@ func TestSolution(t *testing.T) {
3030 }
3131}
3232
33- // 压力测试
33+ // 压力测试
3434func BenchmarkSolution (b * testing.B ) {
3535}
3636
37- // 使用案列
37+ // 使用案列
3838func ExampleSolution () {
3939}
You can’t perform that action at this time.
0 commit comments