温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetcode 409:给定字符串,求能重组成的最长回文字符串

发布时间:2020-06-11 02:07:36 来源:网络 阅读:197 作者:Jayce_SYSU 栏目:编程语言
# -*- coding: utf-8 -*-
# @Time         : 2019-10-11 10:56
# @Author       : Jayce Wong
# @ProjectName  : job
# @FileName     : longestPalindrome.py
# @Blog         : https://blog.51cto.com/jayce1111
# @Github       : https://github.com/SysuJayce

"""
Given a string which consists of lowercase or uppercase letters, find the
length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
"""

class Solution:
    """
    给定一个字符串,问其中的字符最多能组成多长的回文字符串?

    其实我们可以这样想,所谓的回文字符串,就是从左到右和从右到左的遍历是一样的,那么就是说,
    每个字符都需要出现偶数次,当然,如果是奇数长度的回文字符串,其中间的字符可以是只出现了一次。

    也就是说,我们只需要判断给定的字符串中各个字符的出现次数,把偶数次的字符挑出来,然后从奇数次的
    字符中找一个(如果存在出现次数为奇数的字符的话),这些字符就能组成最长的回文字符串。
    """
    def longestPalindrome(self, s: str) -> int:
        from collections import Counter
        # 找出所有奇数次的字符
        odds = sum(v & 1 for v in Counter(s).values())
        # 先把奇数次的字符去掉,然后从中找一个(如果有)
        return len(s) - odds + bool(odds)
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI