1.題目描述(難度Easy)
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.
2.題目分析
題目要求的在一個(gè)給定的字符串且字符串范圍是大小寫(xiě)字母,找出可以組成最大回文字符串的長(zhǎng)度乘陪。
回文(palindrome)需要滿(mǎn)足的條件,是字符串對(duì)稱(chēng),而對(duì)稱(chēng)字符串就說(shuō)明同個(gè)字符出現(xiàn)的個(gè)數(shù)是偶數(shù)個(gè)(至多有一個(gè)奇數(shù)字符)民褂。
那么問(wèn)題就轉(zhuǎn)化為字符串里的字符計(jì)數(shù)問(wèn)題。
解題思路:
對(duì)字符串中的字符計(jì)數(shù)。兩種方法可選:
- 使用計(jì)數(shù)器 collections之counter
- 使用字典對(duì)字符計(jì)數(shù)
3.解題過(guò)程
Begin(算法開(kāi)始)
輸入 字符串string
對(duì)于string中的字符計(jì)數(shù)
palindrome_len = 0
? 遍歷計(jì)數(shù)器:
??if count%2==0:
???palindrome_len += count
??else:
???palindrome_len += count-1
IF有基數(shù)count return palindrome_len+1
ELSE return palindrome_len
End (算法結(jié)束)
具體代碼(python)已對(duì)應(yīng)實(shí)現(xiàn),如上述思路有不足之處請(qǐng)批評(píng)指正鸿摇。