leetcode 每日签到 409. 最长回文串

题目:

最长回文串

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

注意:
假设字符串的长度不会超过 1010。

示例 1:

输入:
"abccccdd"

输出:
7

解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
来源:leetcode
链接:https://leetcode-cn.com/problems/longest-palindrome/
代码:

class Solution:
    def longestPalindrome(self, s: str) -> int:
        a=collections.Counter(s)
        num=0
        count=0
        if  len(a)==1:
            return  len(s)
        for i in a:
            if a[i]%2==0:
                num+=a[i]
            elif a[i]>1:
                num+=a[i]-1
                count=1
            else:
                count=1
        return num+count if len(s)!=0 else 0

大神代码:

class Solution:
    def longestPalindrome(self, s):
        ans = 0
        count = collections.Counter(s)
        for v in count.values():
            ans += v // 2 * 2
            if ans % 2 == 0 and v % 2 == 1:
                ans += 1
        return ans

猜你喜欢

转载自www.cnblogs.com/rmxob/p/12522601.html
今日推荐