leetcode-最长回文串

409. 最长回文串

题解:

  1. 统计每个字符出现的次数。
  2. 回文字符串的特点是,除了最中间的一个字符可以出现一次外,其他字符都应该成对出现(即出现次数为偶数)来保持对称。
  3. 遍历字符出现的次数,将偶数次全部计入最长回文串的构造中。对于奇数次出现的字符,将其次数减一变成偶数后加入到回文串中,如果回文串中还没有中心字符,可以把其中一个奇数次字符整体加入到回文串中作为中心。
python 复制代码
class Solution:
    def longestPalindrome(self, s: str) -> int:
        char_count = {}
        for char in s:
            char_count[char] = char_count.get(char, 0) + 1
        # 初始化回文串的长度为0
        length = 0

        # 标记是否已加入中心字符
        center_added = False
        for count in char_count.values():
            if count % 2 == 0:
                length += count
            else:
                # 如果出现奇数次,并且还没有中心字符,
                # 可以选择一个作为中心,因此总长度+1
                # 同时将剩余的偶数部分加入长度
                if not center_added:
                    length += 1
                    center_added = True
                length += count - 1
        return length
相关推荐
alphaTao9 小时前
LeetCode 每日一题 2026/9/21-2026/9/27
python·算法·leetcode
Persistent的粽子!21 小时前
双指针算法:最大盛水容器
c++·算法·leetcode
All for pursuit.1 天前
【二叉树-10】114.二叉树展开为链表
数据结构·c++·算法·leetcode·链表
旖旎夜光7 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger7 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂7 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_107 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_37 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z7 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.7 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode