Overview
Given a string s consisting of lowercase and/or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case-sensitive.
Constraints
1 <= s.length <= 2000sconsists of lowercase and uppercase English letters.
Examples
longestPalindrome("abccccdd");
// => 7 (e.g. "dccaccd")
longestPalindrome("a");
// => 1Solution
Reveal solution
function longestPalindrome(s) {
const freq = {};
for (const c of s) freq[c] = (freq[c] || 0) + 1;
let length = 0;
let hasOdd = false;
for (const count of Object.values(freq)) {
length += Math.floor(count / 2) * 2;
if (count % 2 === 1) hasOdd = true;
}
return hasOdd ? length + 1 : length;
}Count character frequencies. Use pairs for both sides, and add one odd character in the center if any exist.
Resources
longest-palindrome-build.js
Longest Palindrome
easycodingAlgorithmsHash Map
Overview
Given a string s consisting of lowercase and/or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case-sensitive.
Constraints
1 <= s.length <= 2000sconsists of lowercase and uppercase English letters.
Examples
longestPalindrome("abccccdd");
// => 7 (e.g. "dccaccd")
longestPalindrome("a");
// => 1Solution
Reveal solution
function longestPalindrome(s) {
const freq = {};
for (const c of s) freq[c] = (freq[c] || 0) + 1;
let length = 0;
let hasOdd = false;
for (const count of Object.values(freq)) {
length += Math.floor(count / 2) * 2;
if (count % 2 === 1) hasOdd = true;
}
return hasOdd ? length + 1 : length;
}Count character frequencies. Use pairs for both sides, and add one odd character in the center if any exist.
Resources
NameTopicDifficulty
103 of 103 problems