409.最长回文串
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
字符串的长度不会超过 1010。
class Solution:
def longestPalindrome(self, s: str) -> int:
ans = odd = 0
cnt = collections.Counter(s)
for c in cnt:
ans += cnt[c]
if cnt[c] % 2 == 1:
ans -= 1
odd += 1
return ans + (odd > 0)
"""
回文顶多一个奇数
统计每个字母的出现次数:
若字母出现偶数次,则直接累加至最终结果
若字母出现奇数次,则将其值-1变成偶数次之后累加至最终结果
若存在出现奇数次的字母,将最终结果+1
"""