topic:
The longest palindrome string
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:
Enter:
"abccccdd"
Output:
7
Explanation:
we can construct the longest string is palindrome "dccaccd", its length is 7.
Source: leetcode
link: https://leetcode-cn.com/problems/longest-palindrome/
Code:
class Solution:
def longestPalindrome(self, s: str) -> int:
a=collections.Counter(s)
num=0
count=0
if len(a)==1:
return len(s)
for i in a:
if a[i]%2==0:
num+=a[i]
elif a[i]>1:
num+=a[i]-1
count=1
else:
count=1
return num+count if len(s)!=0 else 0
Great God Code:
class Solution:
def longestPalindrome(self, s):
ans = 0
count = collections.Counter(s)
for v in count.values():
ans += v // 2 * 2
if ans % 2 == 0 and v % 2 == 1:
ans += 1
return ans