Loading... 这道题跟 [构建回文串检测](https://www.snowkagura.com/archives/166.html) 的思路很像,因为都是统计字符个数,然后看构造回文串的条件。 因为是构造最长的回文串,所以思路略微有点不同,碰到字符频次为奇数的需要加上其频次 - 1 的长度,然后有奇数频次的字符,则可以在中间再加上一个字符。 ```go func longestPalindrome(s string) int { cnt := map[byte]int{} for i := range s { cnt[s[i]]++ } res := 0 hasOdd := false for _, v := range cnt { res += (v / 2) * 2 if v % 2 == 1 { hasOdd = true } } if hasOdd { res++ } return res } ``` Last modification:July 13, 2025 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏