1.Description
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.
Subscribe to see which companies asked this question.
解读
给定一个字符串,求解能够重组成最长的回文序列
2.Solution
可以观察得到,能够构成回文的最长长度为len-出现奇次字母次数和+bool(odds)
def longestPalindrome(self, s):
odds = sum(v & 1 for v in collections.Counter(s).values())
return len(s) - odds + bool(odds)
观察下面的序列:
aaba
→
aba a:3,b:1,奇次sum为2,总数为4, 4-2+1=3次
ab
→
a 其中,a:1,b:1,奇次sum为2,总数为2, 2-2+1=1次