Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add solution and test-cases for problem 132 #1083

Merged
merged 1 commit into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions leetcode/101-200/0132.Palindrome-Partitioning-II/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# [132.Palindrome Partitioning II][title]

## Description
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 1:**

```
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
```

**Example 2:**

```
Input: s = "a"
Output: 0
```

**Example 3:**

```
Input: s = "ab"
Output: 1
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/palindrome-partitioning-ii/
[me]: https://github.com/kylesliu/awesome-golang-algorithm
42 changes: 40 additions & 2 deletions leetcode/101-200/0132.Palindrome-Partitioning-II/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(s string) int {
cache := map[string]int{}
var (
dfs func(string) int
isPalindrome func(string) bool
)
isPalindrome = func(s string) bool {
l, r := 0, len(s)-1
for ; l < r; l, r = l+1, r-1 {
if s[l] != s[r] {
return false
}
}
return true
}
dfs = func(cur string) int {
l := len(cur)
if l == 0 || l == 1 {
return 0
}
if v, ok := cache[cur]; ok {
return v
}
if isPalindrome(cur) {
cache[cur] = 0
return 0
}
m := -1
for end := 1; end < len(cur); end++ {
if isPalindrome(cur[:end]) {
r := dfs(cur[end:]) + 1
if m == -1 || m > r {
m = r
}
}
}
cache[cur] = m
return m
}
return dfs(s)
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs string
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", "aab", 1},
{"TestCase2", "a", 0},
{"TestCase3", "ab", 1},
}

// 开始测试
Expand All @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading