当前位置:网站首页>409. longest palindrome

409. longest palindrome

2022-07-01 03:44:00 Sun_ Sky_ Sea

409. Longest palindrome

Original title link :https://leetcode.cn/problems/longest-palindrome/

Given a string of uppercase and lowercase letters s , return Constructed from these letters The longest palindrome string .

In the process of construction , Please note that Case sensitive . such as “Aa” Can't be treated as a palindrome string .

Example 1:

Input :s = “abccccdd”
Output :7
explain :
The longest palindrome string we can construct is "dccaccd", Its length is 7.
Example 2:

Input :s = “a”
Input :1
Example 3:

Input :s = “bb”
Input : 2

Tips :

1 <= s.length <= 2000
s Only lowercase and / Or capital letters

Their thinking :

Count the number of characters , Even numbers of characters can be placed on either side , The odd number of characters can only be used once , Among them, even characters are placed on both sides , One remaining character , Put it in the middle as the dividing line .

Code implementation :

class Solution:
    def longestPalindrome(self, s: str) -> int:
        #  Statistics string s The number of each character of 
        import collections
        count = collections.Counter(s)
        ans = 0

        for value in count.values():
            #  Take an even number of characters each time and put them on both sides of the palindrome string 
            # ans The number of characters used in the record , Length of palindrome string 
            ans += value // 2 * 2

            #  If value If it's an odd number , Then use this odd string once 
            #  because value The even number of characters in can be placed on both sides of the palindrome string 
            #  The rest can be placed in the middle of the palindrome string as the dividing line 
            #  Such a number is an odd number of characters can only use one , Otherwise, it will not form a palindrome string 
            if ans % 2 == 0 and value % 2 == 1:
                ans += 1
            
        return ans
原网站

版权声明
本文为[Sun_ Sky_ Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010323231715.html