Leetcode 409. Longest Palindrome

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.

思路:先用hash table统计每个字母出现多少次。中间应该是放最长的并出现奇数次的那些字母。例如:abcccdb, ans = bcccb。注意这个情况 aaaccccc,这一题的答案是accccca,而不是ccccc。所以update maxOdd时要将去掉的old maxOdd除以二加到ans里面去。

 

 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         letters = collections.Counter(s)
 8         maxOdd = 0
 9         ans = 0
10         for letter in letters:
11             if letters[letter]%2 == 1 and letters[letter] > maxOdd:
12                 ans += maxOdd//2
13                 maxOdd = letters[letter]
14             else:
15                 ans += letters[letter]//2
16         return 2*ans + maxOdd

 

posted @ 2017-01-17 02:23  lettuan  阅读(135)  评论(0编辑  收藏  举报