
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Length of the Longest Possible Palindrome String in JavaScript
Given a string s which consists of lowercase or uppercase letters, we are required to 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 here.
For example −
If the input string is −
const str = "abccccdd";
then the output should be 7,
because, one longest palindrome that can be built is "dccaccd", whose length is 7.
Example
const str = "abccccdd"; const longestPalindrome = (str) => { const set = new Set(); let count = 0; for (const char of str) { if (set.has(char)) { count += 2; set.delete(char); } else { set.add(char); } } return count + (set.size > 0 ? 1 : 0); }; console.log(longestPalindrome(str));
Output
And the output in the console will be −
7
Advertisements