下面是使用Go语言实现的最长回文子串的代码示例:
func longestPalindrome(s string) string {
if len(s) < 2 {
return s
}
start, end := 0, 0
for i := 0; i < len(s); i++ {
len1 := expandAroundCenter(s, i, i)
len2 := expandAroundCenter(s, i, i+1)
length := max(len1, len2)
if length > end-start {
start = i - (length-1)/2
end = i + length/2
}
}
return s[start : end+1]
}
func expandAroundCenter(s string, left int, right int) int {
L, R := left, right
for L >= 0 && R < len(s) && s[L] == s[R] {
L--
R++
}
return R - L - 1
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
你可以调用 longestPalindrome 函数,将需要检测的字符串作为参数传入,即可获取到最长回文子串。
内容由零声教学AI助手提供,问题来源于学员提问




