Leetcode 409. longest palindrome string ---- python

1. Title Description

Given a capital letter and lowercase letter string comprising, configured to find the longest by letters palindromic sequence.
In the construction process, please note case sensitive. Such as "Aa" can not be used as a palindrome string.
Note :
assuming that the length of the string is not more than 1,010.

Example 1 :
Input:
"abccccdd"
Output:
7
Explanation:
We can construct the longest string is palindrome "dccaccd", its length is 7.

2. Problem-solving ideas

Palindromic sequence features :
a palindromic sequence that either the total length of an even number may be odd
, such as: CAAC (total length is an even number)
, such as: CCACC (total length is an odd number)

This results in problem-solving ideas :
(1) If the number of occurrences of the string of letters to the count is an even number, then can be formed directly palindromic
(2) if the given string of letters Masterpieces occurrences count, the count can be chosen -1 as palindromic, finally, returning the total length of the longest string palindromic time plus 1 indicates the maximum put a palindromic sequence intermediate odd number of occurrences of the letter

For example :
the given string: atttnrca
wherein each of the number of occurrences of the letters: a: 2, t: 3 , n: 1, r: 1, c: 1
up is formed of a palindromic sequence may be: AT T TA

3. code implementation

class Solution:
    def longestPalindrome(self, s: str) -> int:
        flag = False#用来判断是否有出现次数为奇数的
        sumCount = 0#累计字母出现次数
        setS = set(s)
        #若字符串个数为1或字符串类似于‘ccc’,则直接返回字符串的长度
        if(len(setS) == 1):
            return len(s)
        for i in setS:
            if(s.count(i)%2 == 0):#若字母出现次数为偶数次,则直接相加次数
                sumCount = sumCount + s.count(i)
            else:#若字母出现次数为奇数次,则可以每次取该字母的偶数个数,形成对称
                sumCount = sumCount + s.count(i) - 1
                flag = True
        if(flag):#如果有出现次数为奇数的,则可以选择奇数中的一个字母放在字符串的中间,所以加1
            return sumCount + 1
        else:
            return sumCount

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/u013075024/article/details/93309852