Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. You are given a string consisting of lower and upper case characters.
  3. You need to find the length of the longest palindrome which you can create by using the characters from the string.
  4. Note: Upper case and lower case characters are different from each other i.e, "Aa" is not a palindrome as 'A' != 'a'.
  5.  
  6. Input format
  7. There are 2 lines of input
  8.  
  9. First line contains the size of the string
  10.  
  11. Second line contains the string.
  12.  
  13. Output format
  14. Print the length of the longest palindrome possible.
  15.  
  16. Sample Input 1
  17. 4 bbde
  18.  
  19. Sample Output 1
  20. 3
  21.  
  22. Explanation
  23. The possible 3 size palindrome strings are :- beb and bdb
  24.  
  25. Constraints
  26. 1 <= Size of String <= 10^4
  27. */
  28.  
  29. function getIndex(char){
  30.   return Math.floor(char.charCodeAt(0));
  31. }
  32.  
  33. /**
  34.  * @param {number} n
  35.  * @param {string} s
  36.  * @return {number}
  37.  */
  38. // solve simply by using hashing : hash[256] for all characters
  39. function longestPalindrome(n, str) {
  40.     let hash=new Array(256).fill(0);
  41.     let ans=0;
  42.    for(let i=0;i<n;i++){
  43.        hash[getIndex(str[i])]++;
  44.    }
  45.     for(let i=0;i<256;i++){
  46.         if(hash[i]&1==1)
  47.         {
  48.             ans+=Math.floor(hash[i]-1);
  49.             hash[i]=1;
  50.         }
  51.         else{
  52.             ans+=hash[i];
  53.             hash[i]=0;
  54.         }
  55.     }
  56.  
  57.     for(let i=0;i<256;i++){
  58.         if(hash[i]==1){
  59.             ans++;
  60.             break;
  61.         }
  62.     }
  63.     return ans;
  64.    
  65.  
  66. }
  67.  
  68. function main() {
  69.     const n = parseInt(readLine())
  70.     const str = readLine()
  71.     const result = longestPalindrome(n, str)
  72.     console.log(result)
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement