题目
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa"
is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
思路
用一个字典记录每个字符出现的次数,然后如果出现奇数次大于0则减去奇数次减1。
代码
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
n={}
for x in s:
if x in n.keys():
n[x]+=1
else:
n[x]=1
a=0
c=0
for x in n.values():
a+=x
if x%2==1:
c+=1
if c>0:
c-=1
return a-c
结果