package main
func longestPalindrome(s string) string { if len(s) < 2 { return s } newS := make([]rune, 0) newS = append(newS, '#') for _, c := range s { newS = append(newS, c) newS = append(newS, '#') } dp, maxRight, center, maxlen, begin := make([]int, len(s)), 0, 0, 1, 0 for i := 0; i < len(newS); i++ { if i < maxRight { dp[i] = min(maxRight-i, dp[2*center-i]) } left, right := i-(1+dp[i]), i+(1+dp[i]) for left >= 0 && right < len(newS) && newS[left] == newS[right] { dp[i]++ left-- right++
} if i+dp[i] > maxRight { maxRight = i + dp[i] center = i } if dp[i] > maxRight { maxRight = i + dp[i] center = i }
if dp[i] > maxlen { maxlen = dp[i] begin = (i - maxlen) / 2 } } return s[begin : begin+maxlen]
} func min(a int, b int) int { if a < b { return a } return b } func main() { longestPalindrome("babad") }
func longestPalindrome2(s string) string { res := "" for i := 0; i < len(s); i++ { res = maxPalindrome(s, i, i, res) res = maxPalindrome(s, i, i+1, res)
} return res
} func maxPalindrome(s string, i, j int, res string) string { sub := "" for i >= 0 && j < len(s) && s[i] == s[j] { sub = s[i : j+1] i-- j++
} if len(res) < len(sub) { return sub } return res }
|