5. 最长回文子串
最后更新于
最后更新于
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。输入:s = "cbbd"
输出:"bb"func longestPalindrome(s string) string {
n := len(s)
dp := make([][]bool, n)
for i:=range dp {
dp[i] = make([]bool, n)
dp[i][i] = true
}
start, max := 0, 1
for i := n-2; i >= 0 ; i-- {
for j := i+1; j < n; j++ {
if s[i] == s[j] {
if j-i < 3 {
dp[i][j] = true
}else{
dp[i][j] = dp[i+1][j-1]
}
}
if dp[i][j] && j-i+1>max {
start = i
max = j-i+1
}
}
}
return s[start:start+max]
}