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.
Go语言
package main
import “fmt”
func longestPalindrome(s string) int {
var m = make(map[byte]int)
// 如果存在就+1,如果不存在就等于1
for i := 0; i < len(s); i++ {
if _, ok := m[s[i]]; ok {
m[s[i]] = m[s[i]] + 1
} else {
m[s[i]] = 1
}
}
var sum = 0
var more = 0
var palindrome = make(map[byte]int)
// value大于2的,除以2再*2,这样可以避免奇数的勤劳的
// 同时这样的奇数还可能充当回文中的字符
// 所以定义more判断是否有这样的字符
for k, v := range m {
if v >= 2 {
palindrome[k] = v
sum = sum + (palindrome[k]/2)*2
if palindrome[k] % 2 != 0 {
more = more + 1
}
}
}
fmt.Println(m)
fmt.Println(palindrome)
if len(palindrome) < (len(m)+more) {
return sum+1
} else {
return sum
}
}
func main() {
fmt.Println(longestPalindrome("abccccdd"))
}
[/go]