funclongestPalindrome(s string)string { n := len(s)
dp := make([][]bool, n) for i := range dp { dp[i] = make([]bool, n) }
for i := 0; i < n; i++ { dp[i][i] = true }
maxLen := 1 start := 0
// 遍历所有可能的子串长度 l for l := 2; l <= n; l++ { // 遍历所有可能的开始位置 i for i := 0; i < n; i++ { j := l + i - 1 if j >= n { break } if s[i] != s[j] { dp[i][j] = false } else { if j - i + 1 <= 3 { // 如果子串长度为 2 或 3,则一定是回文串 dp[i][j] = true } else { dp[i][j] = dp[i+1][j-1] } }
// 更新最长子串 if dp[i][j] && j - i + 1 > maxLen { maxLen = j - i + 1 start = i } } }
funclongestPalindrome(s string)string { if s == "" { return"" } start, end := 0, 0 for i := 0; i < len(s); i++ { left1, right1 := expandAroundCenter(s, i, i) left2, right2 := expandAroundCenter(s, i, i + 1) if right1 - left1 > end - start { start, end = left1, right1 } if right2 - left2 > end - start { start, end = left2, right2 } } return s[start:end+1] }
funcexpandAroundCenter(s string, left, right int)(int, int) { for ; left >= 0 && right < len(s) && s[left] == s[right]; left, right = left-1 , right+1 { } return left + 1, right - 1 }