力扣(leetcode)第409题最长回文串(Python)

409.最长回文串

题目链接:409.最长回文串

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

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

示例 1:
输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

示例 2:
输入:s = “a”
输出:1

示例 3:
输入:s = “aaaaaccc”
输出:7

提示:

1 <= s.length <= 2000
s 只由小写 和/或 大写英文字母组成

解答一

class Solution:
    def longestPalindrome(self, s: str) -> int:
        counter = collections.defaultdict(int)
        for c in s:
            counter[c] += 1
        res, odd = 0, 0
        for count in counter.values():
            rem = count % 2
            res += count - rem
            if rem == 1: odd = 1
        return res + odd

解答二


class Solution:
    def longestPalindrome(self, s: str) -> int:
        if len(s) == 1:
            return 1
        res = []
        count = 0
        d = set(s)
        for i in d:
            if s.count(i) >= 2:
                count = count + s.count(i) // 2
                if s.count(i) %2 != 0:
                    res.append(i)
            else:
                res.append(i)
        if len(res) != 0:
            return count*2 + 1
        else:
            return count*2
            

最后,我写了一篇MySQL教程,里面详细的介绍了MySQL的基本概念以及操作指令等内容,欢迎阅读!
MySQL数据库万字保姆级教程

  • 23
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值