Leetcode 409. Longest Palindrome
Given a string s
which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
Letters are case sensitive, for example, "Aa"
is not considered a palindrome here.
To form the longest palindrome, consider the following steps:
frequency - 1
to the length (to make it even).#include <iostream>
#include <unordered_map>
#include <string>
int longestPalindrome(std::string s) {
std::unordered_map<char, int> charCount;
// Count the frequency of each character
for (char ch : s) {
charCount[ch]++;
}
int length = 0;
bool oddIncluded = false;
// Calculate the maximum length of the palindrome
for (const auto& pair : charCount) {
if (pair.second % 2 == 0) {
length += pair.second;
} else {
length += pair.second - 1;
oddIncluded = true;
}
}
// Add one for the central odd character if there was an odd count
if (oddIncluded) {
length += 1;
}
return length;
}
int main() {
std::string input = "abccccdd";
std::cout << "Length of the longest palindrome: " << longestPalindrome(input) << std::endl;
return 0;
}
The time complexity of this solution is O(n)
, where n
is the length of the input string s
.
This ensures the solution is efficient for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?