funclongestPalindrome(s string)string { var ( subStr = "" lenS int index int subK int maxLeftIndex int maxRightIndex int ) lenS = 2*len(s) - 1 for index < lenS { subK = 0 for { leftIndex, rightIndex := index-subK, index+subK if leftIndex%2 != 0 { leftIndex-- } if rightIndex%2 != 0 { rightIndex++ } if leftIndex < 0 || rightIndex >= lenS { break } if s[leftIndex/2] == s[rightIndex/2] { if maxRightIndex-maxLeftIndex < rightIndex/2-leftIndex/2 { maxLeftIndex, maxRightIndex = leftIndex/2, rightIndex/2 } subK++ } else { break } } index++ } if maxRightIndex < len(s) { subStr = s[maxLeftIndex:maxRightIndex+1] } return subStr }
本地测试
package main
import"fmt"
funcmain() { s := "babad" fmt.Println(longestPalindrome(s)) s = "cbbd" fmt.Println(longestPalindrome(s)) s = "abcd" fmt.Println(longestPalindrome(s)) s = "cbbb" fmt.Println(longestPalindrome(s)) s = "bbbc" fmt.Println(longestPalindrome(s)) s = "ababa" fmt.Println(longestPalindrome(s)) s = "bbbb" fmt.Println(longestPalindrome(s)) }