LeetCode 409: Longest Palindrome Solution
Master LeetCode problem 409 (Longest Palindrome), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
409. Longest Palindrome
Problem Explanation
Explanation:
To find the length of the longest palindrome that can be built with the given letters, we need to count the frequency of each letter in the input string. A palindrome can have an even count of each character, and at most one character can have an odd count (which will be placed in the middle of the palindrome). Hence, we can iterate over the counts of each character and calculate the length of the palindrome accordingly.
- Initialize a variable
lengthto store the length of the longest palindrome. - Iterate over the counts of each character in the input string.
- For each character count, add the maximum even count (characterCount // 2 * 2) to the
length. - If there is any character with an odd count, add 1 to the
length(as it can be placed in the middle of the palindrome). - Return the final
length.
Time Complexity: O(n) where n is the length of the input string s. Space Complexity: O(1) since we are using a constant amount of space to store the counts of characters.
Solution Code
class Solution {
public int longestPalindrome(String s) {
int[] charCounts = new int[128];
for (char c : s.toCharArray()) {
charCounts[c]++;
}
int length = 0;
for (int count : charCounts) {
length += count / 2 * 2;
}
if (length < s.length()) {
length++; // Add 1 for a single character that can be placed in the middle
}
return length;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 409 (Longest Palindrome)?
This page provides optimized solutions for LeetCode problem 409 (Longest Palindrome) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 409 (Longest Palindrome)?
The time complexity for LeetCode 409 (Longest Palindrome) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 409 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 409 in Java, C++, or Python.