https://leetcode.cn/problems/longest-palindrome/
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
示例 1:
输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
class Solution:
def longestPalindrome(self, s: str) -> int:
# 难度:☆☆☆
# 方法1:贪心
# from collections import Counter
# cnt = 0
# dic = Counter(s)
# for i in dic.values(): # 遍历每个字符出现的次数
# # 如果这个字符是偶数个,那么直接使用i个
# # 如果这个字符是奇数个,那么使用i - 1个
# # 将以上2种情况全部考虑,使用一个公式就是 i // 2 * 2 个
# cnt += i // 2 * 2
# # 如果是abba就没有必要下面的if了
# # 如果是abcba,就要给abba插入一个中间元素,也就是找个奇数的字符
# # 这种情况只能用1次,也就是目前cnt是偶数,但是遍历元素是奇数个
# if cnt % 2 == 0 and i % 2 == 1:
# cnt += 1
# return cnt
# 方法2:借助列表
# 该方法的好处是可以输出最长回文串是什么
evens = [] # 偶数个字符的列表
odds = [] # 奇数个字符的列表
import collections
dic = collections.Counter(s)
for k, v in dic.items():
if v >= 2:
evens.append(k * (v // 2))
if v % 2 == 1:
odds.append(k)
evens.sort() # 如要输出字典序最小的回文,则要sort,否则无需
lefts = ''.join(evens)
mids = ''
if odds:
odds.sort()# 如要输出字典序最小的回文,则要sort,否则无需
mids = odds[0]
return 2 * len(lefts) + len(mids)
# return lefts + mids + lefts[::-1] # 输出最长回文串是什么