from collections import Counter
class Solution :
"""
@param s: a string which consists of lowercase or uppercase letters
@return: the length of the longest palindromes that can be built
"""
def longestPalindrome(self, s) :
n = len(s)
if n == 0 :
return 0
if n == 2 :
if s[0] == s[1] :
return n
else :
return 1
counts = Counter(s)
even_strings_sum = sum(val for _, val in counts.items() if val % 2 == 0)
odd_strings = sorted(val for key, val in counts.items() if val % 2 == 1)
odd_strings_sum_even = sum(val - 1 for val in odd_strings[:-1] if val > 1)
if odd_strings :
odd_strings_sum = odd_strings[-1]
else :
odd_strings_sum = 0
return even_strings_sum + odd_strings_sum + odd_strings_sum_even
解题思路
这里直接对所有的字符串数量进行统计,我们直接运用了,collections 模块下的 Counter 方法进行统计!
1:回文串两侧存在的字符串为偶数。
2:中间对称的为奇数。
3:我们假设中间的字符串为单个字符。
4:分开统计偶数字符串和奇数字符串。
5:奇数字符串大于1的,至少为三,换句话说,如果统计出来的字符串 >= 3 我们可以取出最大的一个直接放到回文串的中间,如果大于等于3的数字大于一个,我们则要对其余的进行重新统计,每一个字符都减去1,进而让其编程偶数,在进行操作运算,即可!