Leetcode - Longest Palindrome
https://leetcode.com/problems/longest-palindrome/
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.
func longestPalindrome(s string) int { hash := map[byte]int{} for i := 0; i < len(s); i++ { hash[s[i]]++ } fmt.Println("hash: ", hash) count := 0 maxOddCount := 0 for _, val := range hash { if val % 2 == 1 { if val > maxOddCount { maxOddCount = val } } } maxOddFound := false for _, val := range hash { if val % 2 == 1 { if !maxOddFound && val == maxOddCount { maxOddFound = true continue } if maxOddFound || val != maxOddCount { count += val - 1 } } else { count += val } } return maxOddCount+count }
There is something should be noticed
1. Only count in maxOddCount is not enough
2. Only count even count and with one odd count is not enough
3. There might be many maxOddCount. Only one maxOddCount should be counted in