这道题相对简单,两版代码有细微差别,思想不变,时间复杂度不变。
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
注意:假设字符串的长度不会超过 1010。
示例 :
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7
链接:https://leetcode-cn.com/problems/longest-palindrome
class Solution:
def longestPalindrome(self, s):
length = 0
odds = False
myset = set(s)
for i in myset:
counts = s.count(i)
length += (counts//2*2)
if not odds:
if counts%2==1:
odds = True
if not odds:
return length
else:
return (length+1)
遍历寻找每个字符在整个字符串出现的次数;
出现的次数*2//2就是该字符串支持组成的回文串长度;
所有字母支持的回文串长度加起来,判断是否还有剩余字符,若有,再加一。
class Solution:
def longestPalindrome(self, s):
length = 0
myset = set(s)
for i in myset:
length += (s.count(i)//2*2)
if length == len(s):
return length
else:
return (length+1)