Skip to content

Commit 9cbe21d

Browse files
authored
Merge pull request #1083 from 0xff-dev/132
Add solution and test-cases for problem 132
2 parents 02fd03c + 665c07a commit 9cbe21d

File tree

3 files changed

+82
-9
lines changed

3 files changed

+82
-9
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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
Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,43 @@
11
package 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
}

leetcode/101-200/0132.Palindrome-Partitioning-II/Solution_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff 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+
// 压力测试
3434
func BenchmarkSolution(b *testing.B) {
3535
}
3636

37-
// 使用案列
37+
// 使用案列
3838
func ExampleSolution() {
3939
}

0 commit comments

Comments
 (0)