409. Longest Palindrome
Given a string s which consists of lowercase or uppercase letters, return the length of the longest
palindrome
that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome.
Example 1:
Input: s = “abccccdd”
Output: 7
Explanation: One longest palindrome that can be built is “dccaccd”, whose length is 7.
Example 2:
Input: s = “a”
Output: 1
Explanation: The longest palindrome that can be built is “a”, whose length is 1.
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase English letters only.
From: LeetCode
Link: 409. Longest Palindrome
Solution:
Ideas:
- We use an array char_count to store the frequency of each character in the input string, where the index is determined by the ASCII value of the character.
- We iterate over the string and increment the corresponding value in the array.
- To calculate the longest possible palindrome, we sum the even frequencies directly and subtract 1 from the odd frequencies (since we can use only the largest even part of them).
- If there’s at least one odd frequency, we can place one odd character in the center of the palindrome, so we add 1 to the length.
Code:
int longestPalindrome(char* s) {
int char_count[128] = {
0}; // Array to count occurrences of each character (ASCII size is 128)
int length = 0;
int odd_count = 0;
// Count the occurrences of each character
for (int i = 0; s[i] != '\0'; i++) {
char_count[(int)s[i]]++;
}
// Calculate the length of the longest palindrome
for (int i = 0; i < 128; i++) {
if (char_count[i] % 2 == 0) {
length += char_count[i]; // Add all even counts
} else {
length += char_count[i] - 1; // Add the largest even part of odd counts
odd_count = 1; // There is at least one odd-count character
}
}
// Add 1 to the length if there is any odd-count character, as it can be placed in the middle
return length + odd_count;
}