題目
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.
解題思路
遍歷字符串,將字符和對應出現(xiàn)的次數(shù)放進map中
字符每出現(xiàn)兩次谭跨,則最大回文串長度+2
有一個字符出現(xiàn)是單數(shù),則最大回文串長度再+1
代碼
func longestPalindrome(s string) int {
var length int
len1 := len(s)
if len1 < 2 {
return len1
}
sRune := []rune(s)
var charMap map[rune]int
charMap = make(map[rune]int)
for _, v := range sRune {
charMap[v]++
}
var middle bool
for _, v := range charMap {
if 0 != v % 2 {
middle = true
}
length += v - v%2
}
if middle {
length++
}
return length
}