409. Longest Palindrome

problem

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.

给一串字母,用这些字母组成一个回文串,返回长度

大小写区分,给定的string长度不会超过1010

solution

  • 思路

找元素个数,回文字符串长度是能组成偶数的数量然后加1

当元素个数有奇数时回文字符串长度是能组成偶数的数量然后加1

当所有元素均为偶数时,不用加1

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        min = set(s)
        nums = 0
        sign = 0
        for x in min:
            num = s.count(x)
            nums += num - num % 2
            if num%2 != 0:
                sign = 1
        return nums+sign

discuss

def longestPalindrome(self, s):
    cnt = collections.Counter(s)
    return sum(cnt[n] & (~1) for n in cnt) + int(any(cnt[n] % 2 for n in cnt))
def longestPalindrome(self, s):
    cnt = collections.Counter(s).values()
    return sum(i&~1 for i in cnt) + any(i%2 for i in cnt)
  • 大致思路一致,但是实现的很精巧
  • 使用Counter, (一些记忆模糊了,整理后link)
  • 使用x & (~1)取每个值最近的偶数
  • 使用any判断是否有非偶数存在
posted @ 2016-10-15 15:34  Salmd  阅读(96)  评论(0)    收藏  举报