题目:最长回文
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa"
is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.题意:给一个字符串,包括大写和小写字母,找到能用这些字符构建的最长回文字符串。这里区分大小写,‘Aa’不是一个回文。可以假设字符串长度不超过1010
思路:这里是让找出能用字符串中的字符构建的最长回文,而不是直接在字符串中找最长回文。这里要区分开。
在这道题中,我们可以用个巧法,不去找真正的回文,而是根据回文的特点来求。
回文字符串:从左看和从右看该字符串完全一样,则该字符串为回文字符串。
这里分两种情况:1,字符串长度为奇数,则中间位置的字符出现一次,其余字符在中间字符左右两侧出现相同的次数,即出现偶数次
2,字符串长度为偶数,则所有字符出现的次数为偶数次
我们来统计给定的字符串中各个字符出现的次数,用字典dict存储统计结果,出现一次加1,最后用每个字符出现的次数除以2,如果出现2次以上,则左右两侧可以各放一个或者多个,如果出现一次,可以取一个放在中间,此时最长回文长度为奇数。如果没有出现奇数次的,则此时回文长度为偶数个。
代码:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
adict = {}
length = 0
num1 = 0
for c in s:
if c in adict:
adict[c] += 1
else:
adict[c] = 1
for key in adict.keys():
if adict[key] % 2 != 0:
num1 = 1
if adict[key] / 2 >=1:
length += int(adict[key] / 2)
if num1 == 0:
return length*2
else:
return length*2 +1