Description
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.
Examples:
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.
Solution in Python
To find the length of the longest palindrome that can be built using the characters in a string, we leverage the properties of palindromes:
- Properties of Palindromes:
- A palindrome can have at most one character with an odd count. All other characters must have even counts.
- For example:
- “dccaccd” uses all characters with even counts and includes one character with an odd count in the center.
- Approach:
- Count the frequency of each character in the string.
- Use the even counts entirely since they contribute fully to the palindrome length.
- Use the largest odd count as part of the palindrome (one character in the center) and convert other odd counts into even counts by subtracting 1.
- Steps:
- Count character frequencies using a dictionary or
collections.Counter
. - Iterate through the counts to calculate the maximum possible palindrome length.
- Count character frequencies using a dictionary or
Python
class Solution:
def longestPalindrome(self, s: str) -> int:
# Count the frequency of each character
char_count = Counter(s)
# Initialize the length of the longest palindrome
palindrome_length = 0
odd_found = False
# Iterate over the character frequencies
for count in char_count.values():
if count % 2 == 0:
# Add even counts directly
palindrome_length += count
else:
# Add the largest even part of the odd count
palindrome_length += count - 1
# Flag that an odd count was found
odd_found = True
# If any odd counts were found, one character can be added to the center
if odd_found:
palindrome_length += 1
return palindrome_length
Explanation of the Code:
- Count Frequencies:
- Use
collections.Counter
to count the frequency of each character in O(n), where nnn is the length of the string.
- Use
- Iterate Over Counts:
- For each character count:
- Add the entire count to the palindrome length if it is even.
- If it is odd, add count−1 to the palindrome length (making it even) and flag that an odd count exists.
- For each character count:
- Adjust for Center Character:
- If an odd count exists, add one to the palindrome length to account for one odd character in the center.
- Return Result:
- The result is the maximum possible length of a palindrome that can be built.
Solution in C++
C++
class Solution {
public:
int longestPalindrome(string s) {
// Create a hash map to count the frequency of each character in the string
unordered_map<char, int> charCount;
// Populate the frequency map
for (char c : s) {
charCount[c]++;
}
// Initialize variables to store the length of the longest palindrome
int palindromeLength = 0;
bool oddFound = false;
// Iterate over the frequency map
for (auto pair : charCount) {
int freq = pair.second;
// If the frequency is even, add it fully to the palindrome length
if (freq % 2 == 0) {
palindromeLength += freq;
} else {
// If the frequency is odd, add the largest even part (freq - 1)
palindromeLength += freq - 1;
// Mark that at least one odd frequency exists
oddFound = true;
}
}
// If there was any odd frequency, we can place one odd character in the center of the palindrome
if (oddFound) {
palindromeLength += 1;
}
// Return the computed length of the longest palindrome
return palindromeLength;
}
};
Solution in Javascript
JavaScript
var longestPalindrome = function(s) {
// Create a map to count the occurrences of each character
const charCount = new Map();
// Loop through the string and count the frequency of each character
for (const char of s) {
charCount.set(char, (charCount.get(char) || 0) + 1);
}
// Initialize variables to calculate the palindrome length
let palindromeLength = 0;
let hasOddFrequency = false; // Flag to track if we have at least one odd frequency
// Iterate over the character frequencies
for (const count of charCount.values()) {
// Add the largest even number of characters to the palindrome length
palindromeLength += Math.floor(count / 2) * 2;
// If the count is odd and we don't yet have an odd character, set the flag
if (count % 2 !== 0) {
hasOddFrequency = true;
}
}
// If there is at least one character with an odd count, we can place it in the center
if (hasOddFrequency) {
palindromeLength += 1;
}
// Return the calculated palindrome length
return palindromeLength;
};
Solution in Java
Java
class Solution {
public int longestPalindrome(String s) {
// Step 1: Create a frequency map to count the occurrences of each character
int[] charCounts = new int[128]; // Assuming ASCII characters (128 possible characters)
// Count the occurrences of each character in the string
for (char c : s.toCharArray()) {
charCounts[c]++;
}
// Step 2: Calculate the longest palindrome length
int palindromeLength = 0;
boolean oddCountFound = false; // To track if there is any character with an odd frequency
// Iterate over the frequency array
for (int count : charCounts) {
// If the count is even, add it to the palindrome length
if (count % 2 == 0) {
palindromeLength += count;
} else {
// If the count is odd, add the largest even part (count - 1) to the palindrome length
palindromeLength += count - 1;
oddCountFound = true; // Mark that we found at least one odd frequency
}
}
// Step 3: If there is at least one character with an odd count,
// we can use one of those characters as the center of the palindrome
if (oddCountFound) {
palindromeLength++;
}
// Step 4: Return the calculated palindrome length
return palindromeLength;
}
}