Lintcode 627. Longest Palindrome (Easy) (Python)

Longest Palindrome

Description:

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.

Example
Given s = “abccccdd” return 7

One longest palindrome that can be built is “dccaccd”, whose length is 7.

Code:

class Solution:
    """
    @param s: a string which consists of lowercase or uppercase letters
    @return: the length of the longest palindromes that can be built
    """
    def longestPalindrome(self, s):
        # write your code here
        dict = {}
        cnt = 0
        for i in s:
            dict[i]=1 if i not in dict else dict[i]+1
        for i in dict:
            cnt=cnt+dict[i] if dict[i]%2==0 else cnt+dict[i]-1
        return cnt+1 if cnt<len(s) else cnt

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/81097616