mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge pull request #2643 from markwang1992/131-partition
131.分割回文串增加Go动态规划优化回文串解法
This commit is contained in:
@ -143,7 +143,7 @@ for (int i = startIndex; i < s.size(); i++) {
|
||||
代码如下:
|
||||
|
||||
```CPP
|
||||
// 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法
|
||||
// 判断字符串s在左闭右闭区间[start, end]所组成的数字是否合法
|
||||
bool isValid(const string& s, int start, int end) {
|
||||
if (start > end) {
|
||||
return false;
|
||||
@ -208,7 +208,7 @@ private:
|
||||
} else break; // 不合法,直接结束本层循环
|
||||
}
|
||||
}
|
||||
// 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法
|
||||
// 判断字符串s在左闭右闭区间[start, end]所组成的数字是否合法
|
||||
bool isValid(const string& s, int start, int end) {
|
||||
if (start > end) {
|
||||
return false;
|
||||
|
@ -527,6 +527,7 @@ class Solution:
|
||||
|
||||
```
|
||||
### Go
|
||||
回溯 基本版
|
||||
```go
|
||||
var (
|
||||
path []string // 放已经回文的子串
|
||||
@ -565,6 +566,63 @@ func isPalindrome(s string) bool {
|
||||
}
|
||||
```
|
||||
|
||||
回溯+动态规划优化回文串判断
|
||||
```go
|
||||
var (
|
||||
result [][]string
|
||||
path []string // 放已经回文的子串
|
||||
isPalindrome [][]bool // 放事先计算好的是否回文子串的结果
|
||||
)
|
||||
|
||||
func partition(s string) [][]string {
|
||||
result = make([][]string, 0)
|
||||
path = make([]string, 0)
|
||||
computePalindrome(s)
|
||||
backtracing(s, 0)
|
||||
return result
|
||||
}
|
||||
|
||||
func backtracing(s string, startIndex int) {
|
||||
// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
|
||||
if startIndex >= len(s) {
|
||||
tmp := make([]string, len(path))
|
||||
copy(tmp, path)
|
||||
result = append(result, tmp)
|
||||
return
|
||||
}
|
||||
for i := startIndex; i < len(s); i++ {
|
||||
if isPalindrome[startIndex][i] { // 是回文子串
|
||||
// 获取[startIndex,i]在s中的子串
|
||||
path = append(path, s[startIndex:i+1])
|
||||
} else { // 不是回文,跳过
|
||||
continue
|
||||
}
|
||||
backtracing(s, i + 1) // 寻找i+1为起始位置的子串
|
||||
path = path[:len(path)-1] // 回溯过程,弹出本次已经添加的子串
|
||||
}
|
||||
}
|
||||
|
||||
func computePalindrome(s string) {
|
||||
// isPalindrome[i][j] 代表 s[i:j](双边包括)是否是回文字串
|
||||
isPalindrome = make([][]bool, len(s))
|
||||
for i := 0; i < len(isPalindrome); i++ {
|
||||
isPalindrome[i] = make([]bool, len(s))
|
||||
}
|
||||
for i := len(s)-1; i >= 0; i-- {
|
||||
// 需要倒序计算, 保证在i行时, i+1行已经计算好了
|
||||
for j := i; j < len(s); j++ {
|
||||
if j == i {
|
||||
isPalindrome[i][j] = true
|
||||
} else if j - i == 1 {
|
||||
isPalindrome[i][j] = s[i] == s[j]
|
||||
} else {
|
||||
isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i+1][j-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### JavaScript
|
||||
|
||||
```js
|
||||
|
Reference in New Issue
Block a user