首页 > 其他 > 详细

Leetcode 409. Longest Palindrome

时间:2017-01-17 07:57:02      阅读:208      评论:0      收藏:0      [点我收藏+]

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

 

Leetcode 409. Longest Palindrome

原文:http://www.cnblogs.com/lettuan/p/6291613.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!