Easypython
526bash
56ide
Favoriteui
Share Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.spa
This is case sensitive, for example "Aa" is not considered a palindrome here.code
Note: Assume the length of given string will not exceed 1,010.字符串
Example:string
Input: "abccccdd"it
Output: 7io
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
思路:統計字符串中每一個字母的個數num,計數器count+=num/2,若是個數num有單數,最後組成的迴文長度爲count2+1,若是是複數,最後組成迴文長度爲count2
代碼:python3
class Solution:
def longestPalindrome(self, s):
counter = collections.Counter(s)
count=0
hasSingle=False
for v in counter.values():
if v%2==1:
hasSingle=True
count+=int(v/2)
return count*2+1 if hasSingle else count*2
複製代碼