题目:
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
给定一字串,判断用这个字串的字元为材料,所能组成的最长对称字串的长度
ex:input:"abccccdd"=>output:7
explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
我们建立一个dictionary来记录各字元出现的次数
class Solution: def longestPalindrome(self, s: str) -> int: d={} for i in s: if i in d: d[i]=d[i]+1 else: d[i]=1 ans=0 for i in d: ans=ans+(d[i]//2)*2 if ans%2==0 and d[i]%2==1: ans=ans+1 return ans
判断各个字元一共能凑成几对,每凑成一对表示所能组成的最长回文长度+2
若当前纪录的最长回文长度为偶数,又遇到一字元出现奇数次
则最长回文长度+1(偶数型回文转为奇数型回文,取该字元作为中心)
之后回传我们判断出该字串能组成的最长回文长度
最后执行时间34ms(faster than 92.65%)
那我们下题见