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
相关推荐
Nil20819 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2081 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571971 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂1 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7701 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao2 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1232 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi2 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 天前
leetcode 64最小路径和
算法·leetcode·职场和发展