Longest Palindrome
2018-02-28 本文已影响0人
robin666
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.
Example
Given s = "abccccdd" return 7
One longest palindrome that can be built is "dccaccd", whose length is 7.
思路:
回文串主要有两种形式,一个是左右完全对称的,一种是以中间字符为中心,左右对称。我们使用字典,第一次出现,把元素加入字典,值设为True,再次出现时用del移除元素。结束循环后字典如有元素,则最长是以中间字符为中心左右对称的,即是字符串长度-字典长度+1。
class Solution:
"""
@param s: a string which consists of lowercase or uppercase letters
@return: the length of the longest palindromes that can be built
"""
def longestPalindrome(self, s):
# write your code here
hash = {}
for c in s:
if c in hash:
del hash[c]
else:
hash[c] = True
remove = len(hash)
if remove > 0:
remove -= 1
return len(s) - remove