409. Longest Palindrome
Problem
Return the length of the longest palindrome that can be built by rearranging (a subset of) the letters of s. Letters are case-sensitive, so "Aa" is not a palindrome.
Example: "abccccdd" → 7 (e.g. "dccaccd")
A palindrome uses characters in pairs (one on each side) plus at most one odd character in the middle. Sum the pairs; add 1 if any character is left over.
Complexity: O(n).
class Solution:
def longestPalindrome(self, s: str) -> int:
pairs = sum(v // 2 * 2 for v in Counter(s).values())
return pairs + 1 if pairs < len(s) else pairs
assert Solution().longestPalindrome("abccccdd") == 7
assert Solution().longestPalindrome("a") == 1
assert Solution().longestPalindrome("Aa") == 1
assert Solution().longestPalindrome("bb") == 2
class Solution {
public int longestPalindrome(String s) {
int[] cnt = new int[128];
for (char c : s.toCharArray()) cnt[c]++;
int pairs = 0;
for (int v : cnt) pairs += v / 2 * 2;
return pairs < s.length() ? pairs + 1 : pairs;
}
}
func longestPalindrome(s string) int {
var cnt [128]int
for i := 0; i < len(s); i++ {
cnt[s[i]]++
}
pairs := 0
for _, v := range cnt {
pairs += v / 2 * 2
}
if pairs < len(s) {
return pairs + 1 // one odd letter can sit in the middle
}
return pairs
}