题目

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.

思路

用一个字典记录每个字符出现的次数,然后如果出现奇数次大于0则减去奇数次减1。


代码

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        n={}
        for x in s:
            if x in n.keys():
                n[x]+=1
            else:
                n[x]=1
        a=0
        c=0
        for  x in n.values():
            a+=x
            if x%2==1:
                c+=1
        if c>0:
            c-=1

        return a-c


结果

作业(十五)——409. Longest Palindrome

作业(十五)——409. Longest Palindrome

相关文章:

  • 2022-12-23
  • 2022-02-24
  • 2022-12-23
  • 2021-09-26
  • 2021-05-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
  • 2022-01-06
  • 2022-12-23
相关资源
相似解决方案