Leetcode 409. Longest Palindrome

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 409. Longest Palindrome相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Longest Palindrome

2. Solution

**解析:**Version 1,统计字符个数,偶数的直接相加,奇数的减1相加,存在奇数则最终结果加1,即位于正中间。

  • Version 1
class Solution:
    def longestPalindrome(self, s: str) -> int:
        stat = {}
        for ch in s:
            stat[ch] = stat.get(ch, 0) + 1
        count = 0
        flag = False
        for v in stat.values():
            if v % 2 == 1:
                flag = True
                count += v -1
            else:
                count += v
        if flag:
            count += 1
        return count

Reference

  1. https://leetcode.com/problems/longest-palindrome/

以上是关于Leetcode 409. Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-409-Longest Palindrome]

LeetCode——409. Longest Palindrome

Leetcode_409_Longest Palindrome

[LeetCode&Python] Problem 409. Longest Palindrome

leetcode-409-Longest Palindrome(统计字母出现次数)

Leetcode 409. Longest Palindrome