概述
我们的目标是找到一个字符串中最大的回文子串。例如,我们假设输入的字符串是
cabae
输出应该是aba ,这是最大的回文子串。
我们将使用动态编程来解决这个问题。我们将使用两个矩阵。每个矩阵的大小都是len*len,其中len是输入字符串的大小。
-
第一个矩阵将存储索引**"i "** 和**"j "**之间的子串是否是回文。
-
第二个矩阵将存储**"i "** 和**"j**"之间最长的回文子串**。**
下面是最佳的子结构
- 如果string[i] == string[j],并且i+1和 j-1中的子串是一个回文,那么
len(i,j) = 2 + len(i+1, j-1)
- 如果string[i] != string[j] 那么
len(i,j) = max(len(i+1,j), len(i,j-1)
程序
以下是相同的程序
package main
import (
"fmt"
"math"
"unicode/utf8"
)
func main() {
output := longestPalindrome("cabae")
fmt.Println(output)
}
func longestPalindrome(s string) string {
stringLength := utf8.RuneCountInString(s)
isPalindromeMatrix := make([][]int, stringLength)
for i := range isPalindromeMatrix {
isPalindromeMatrix[i] = make([]int, stringLength)
}
for i, outer := range isPalindromeMatrix {
for j := range outer {
if i == j {
isPalindromeMatrix[i][j] = 1
}
}
}
palindromeLengthMatrix := make([][]int, stringLength)
for i := range palindromeLengthMatrix {
palindromeLengthMatrix[i] = make([]int, stringLength)
}
for i, outer := range palindromeLengthMatrix {
for j := range outer {
if i == j {
palindromeLengthMatrix[i][j] = 1
}
}
}
for len := 2; len <= stringLength; len++ {
for i := 0; i <= stringLength-len; i++ {
j := i + len - 1
if s[i] == s[j] {
if len == 2 {
isPalindromeMatrix[i][j] = 1
palindromeLengthMatrix[i][j] = 2
} else {
if isPalindromeMatrix[i+1][j-1] == 1 {
isPalindromeMatrix[i][j] = 1
palindromeLengthMatrix[i][j] = 2 + palindromeLengthMatrix[i+1][j-1]
} else {
isPalindromeMatrix[i][j] = -1
palindromeLengthMatrix[i][j] = int(math.Max(float64(palindromeLengthMatrix[i+1][j]), float64(palindromeLengthMatrix[i][j-1])))
}
}
} else {
isPalindromeMatrix[i][j] = -1
}
}
}
max_row_index := 0
max_column_index := 0
max := 0
for i, outer := range palindromeLengthMatrix {
for j := range outer {
if palindromeLengthMatrix[i][j] > max && isPalindromeMatrix[i][j] == 1 {
max = palindromeLengthMatrix[i][j]
max_row_index = i
max_column_index = j
}
}
}
return s[max_row_index : max_column_index+1]
}
输出
aba
The postLongest Palindromic Substring within a string in Go (Golang)appeared first onWelcome To Golang By Example.