409.最长回文串
题目链接:409.最长回文串
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
示例 1:
输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = “a”
输出:1
示例 3:
输入:s = “aaaaaccc”
输出:7
提示:
1 <= s.length <= 2000
s 只由小写 和/或 大写英文字母组成
解答一
class Solution:
def longestPalindrome(self, s: str) -> int:
counter = collections.defaultdict(int)
for c in s:
counter[c] += 1
res, odd = 0, 0
for count in counter.values():
rem = count % 2
res += count - rem
if rem == 1: odd = 1
return res + odd
解答二
class Solution:
def longestPalindrome(self, s: str) -> int:
if len(s) == 1:
return 1
res = []
count = 0
d = set(s)
for i in d:
if s.count(i) >= 2:
count = count + s.count(i) // 2
if s.count(i) %2 != 0:
res.append(i)
else:
res.append(i)
if len(res) != 0:
return count*2 + 1
else:
return count*2
最后,我写了一篇MySQL教程,里面详细的介绍了MySQL的基本概念以及操作指令等内容,欢迎阅读!
MySQL数据库万字保姆级教程