Loading

409. 最长回文串

问题描述

给定一个字符串s, 返回由s中字母所构造的最长回文串的长度。

问题分析

符号设定

  • Nch 为ch在回文串中出现的次数
    回文串中最多有一个字符Nch为奇数

算法

class Solution:
    def longestPalindrome(self, s: str) -> int:
        count_ch = {}

        for ch in s:
            if ch not in count_ch:
                count_ch[ ch ] = 1
            else:
                count_ch[ ch ] += 1

        res = 0
        for val in count_ch.values():
            res += val // 2 * 2
            if res % 2 == 0 and val % 2 == 1:
                res += 1

        return res
posted @ 2023-04-17 20:22  Yin-SHT  阅读(18)  评论(0)    收藏  举报