409. Longest Palindrome.md

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.

给定一个由小写或大写字母组成的字符串,找到可以用这些字母构建的最长的回文长度。

这是区分大小写的,例如“Aa”在这里不被视为回文。

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.

python实践

思路1

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 思路:使用字典存储,key:字符,value:字符的个数
        dic = {}
        # 1.初始化字典
        for c in s:
            dic[c] = 0
        for c in s:
            dic[c] += 1
        l = list(dic.values())
        print(l)
        # 2. 依次遍历列表中每一个元素,取模2的余数, 如果一旦出现一个奇数,temp=1
        temp = 0
        for n in l:
            if n % 2 == 1:
                temp = 1
        # 3. 遍历列表,取模2后的整数部分
        # 3.1 初始化
        sum0 = 0
        for r in l:
            sum0 += (r//2) * 2
        print(sum0+temp)
        return sum0 + temp

if __name__ == '__main__':
    s = "abccbccdda"
    Solution().longestPalindrome(s)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦