Longest Palindrome

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.题目分析

题目要求的在一个给定的字符串且字符串范围是大小写字母,找出可以组成最大回文字符串的长度。
回文(palindrome)需要满足的条件,是字符串对称,而对称字符串就说明同个字符出现的个数是偶数个(至多有一个奇数字符)。
那么问题就转化为字符串里的字符计数问题。

解题思路:
对字符串中的字符计数。两种方法可选:

  • 使用计数器 collections之counter
  • 使用字典对字符计数

3.解题过程

Begin(算法开始)
输入 字符串string
对于string中的字符计数
palindrome_len = 0
  遍历计数器:
  if count%2==0:
   palindrome_len += count
  else:
   palindrome_len += count-1
IF有基数count return palindrome_len+1
ELSE return palindrome_len
End (算法结束)

具体代码(python)已对应实现,如上述思路有不足之处请批评指正。

你可能感兴趣的:(Longest Palindrome)