IT源码网

lc409. Longest Palindrome

flyfish 2021年04月03日 程序员 402 0

409. Longest Palindrome

Easy

526

56

Favorite

Share 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.

Example:

Input: "abccccdd"

Output: 7

Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

思路:统计字符串中每个字母的个数num,计数器count+=num/2,如果个数num有单数,最后组成的回文长度为count2+1,如果是复数,最后组成回文长度为count2

代码:python3

class Solution: 
	def longestPalindrome(self, s): 
		counter = collections.Counter(s) 
		count=0 
		hasSingle=False 
		for v in counter.values(): 
			if v%2==1: 
				hasSingle=True 
			count+=int(v/2) 
		return count*2+1 if hasSingle else count*2 
复制代码

转载于:https://juejin.im/post/5d01fd74e51d455a68490b4d


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!