funclongestPalindrome(s string)string { // 1、对每一点进行中央扩散 判断从该点延伸出去最大的回文川是多大 res := "" runes := []rune(s) iflen(runes) <= 1 { return s } for i := 0; i < len(runes); i++ { // 考虑两种情况 // 1、奇数回文 tempOddMaxString := getOddMaxString(runes, i) // 2、偶数回文 tempEvenMaxString := getEvenMaxString(runes, i) tempMaxString := tempEvenMaxString iflen(tempEvenMaxString) < len(tempOddMaxString) { tempMaxString = tempOddMaxString } iflen(tempMaxString) > len(res) { res = tempMaxString } } return res }
funcgetEvenMaxString(runes []rune, i int)string { left := i right := i + 1 for left >= 0 && right <= len(runes)-1 { if left < 0 || right >= len(runes) { returnstring(runes[left:right]) } if runes[left] != runes[right] { returnstring(runes[left+1:right]) } left = left - 1 right = right + 1 } if left < 0 || right >= len(runes) { returnstring(runes[left+1 : right]) } else { returnstring(runes[left : right+1]) }
}
funcgetOddMaxString(runes []rune, i int)string { left, right := i, i for left >= 0 && right <= len(runes)-1 { left = left - 1 right = right + 1 if left < 0 || right >= len(runes) { returnstring(runes[left+1 : right]) } if runes[left] != runes[right] { returnstring(runes[left+1 : right]) } } returnstring(runes[left : right+1]) }