给定一个只包含小写或者大写字母的字符串,寻找用这些字母可以组成的最长回文串的长度。大小写敏感,例如"Aa"在这里不认为是一个回文。
思路:
统计每个字母的出现次数:若字母出现偶数次,则直接累加至最终结果, 若字母出现奇数次,则将其值-1之后累加至最终结果,出现奇数次的字母只算一次
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: 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)
(odd > 0 )为真,ans加1