Leetcode 409.最长回文串
1 题目描述(Leetcode题目链接)
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:假设字符串的长度不会超过 1010。
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
2 题解
统计每个字母出现的次数,长度为所有偶数次数加上所有奇数次数减1,如果有奇数次数则需要在返回值加上1表示中心点。
class Solution:
def longestPalindrome(self, s: str) -> int:
num = dict()
length, center = 0, 0
for char in s:
num[char] = num.get(char, 0) + 1
for key, value in num.items():
if value%2 == 0:
length += value
else:
length += value - 1
center = 1
return length + center
class Solution:
def longestPalindrome(self, s: str) -> int:
num = collections.Counter(s)
length = 0
for i in num:
length += (num[i]//2 * 2)
return length if length == len(s) else length+1