Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- You are given a string consisting of lower and upper case characters.
- You need to find the length of the longest palindrome which you can create by using the characters from the string.
- Note: Upper case and lower case characters are different from each other i.e, "Aa" is not a palindrome as 'A' != 'a'.
- Input format
- There are 2 lines of input
- First line contains the size of the string
- Second line contains the string.
- Output format
- Print the length of the longest palindrome possible.
- Sample Input 1
- 4 bbde
- Sample Output 1
- 3
- Explanation
- The possible 3 size palindrome strings are :- beb and bdb
- Constraints
- 1 <= Size of String <= 10^4
- */
- function getIndex(char){
- return Math.floor(char.charCodeAt(0));
- }
- /**
- * @param {number} n
- * @param {string} s
- * @return {number}
- */
- // solve simply by using hashing : hash[256] for all characters
- function longestPalindrome(n, str) {
- let hash=new Array(256).fill(0);
- let ans=0;
- for(let i=0;i<n;i++){
- hash[getIndex(str[i])]++;
- }
- for(let i=0;i<256;i++){
- if(hash[i]&1==1)
- {
- ans+=Math.floor(hash[i]-1);
- hash[i]=1;
- }
- else{
- ans+=hash[i];
- hash[i]=0;
- }
- }
- for(let i=0;i<256;i++){
- if(hash[i]==1){
- ans++;
- break;
- }
- }
- return ans;
- }
- function main() {
- const n = parseInt(readLine())
- const str = readLine()
- const result = longestPalindrome(n, str)
- console.log(result)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement