Created
September 19, 2016 23:21
-
-
Save anupamkumar/65071d9ee970486e89a9be21a67f9d45 to your computer and use it in GitHub Desktop.
Find longest palindrome formed by removing or shuffling chars from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Find longest palindrome formed by removing or shuffling chars from string | |
// Given a string, find the longest palindrome that can be constructed by removing or shuffling characters from the string. | |
// Return only one palindrome if there are multiple palindrome strings of longest length. | |
// Examples: | |
// Input: abc | |
// Output: a OR b OR c | |
// Input: aabbcc | |
// Output: abccba OR baccab OR cbaabc OR | |
// any other palindromic string of length 6. | |
// Input: abbaccd | |
// Output: abcdcba OR ... | |
// Input: aba | |
// Output: aba | |
////Analysis | |
///// I will parse the string and count the number of occurances of each characters in the strings | |
//// Rules for a string to be a pallindrome: | |
//// At most only one character can occur odd number of times | |
//// All other characters must occur even number of times | |
//// if 2 characters occur at odd number of times then one of them must drop 1 character to make one of it even | |
//// create a pallindrome with the set of characters | |
function parseAndDropChars(str) { | |
var charDict = {}; | |
for(var i=0;i<str.length;i++) { | |
if ( charDict[str[i]] === undefined) { | |
charDict[str[i]] =1; | |
} | |
else { | |
var cur_cnt = charDict[str[i]]; | |
charDict[str[i]] = cur_cnt + 1; | |
} | |
} | |
var odd_cnt=0; | |
for(var ch in charDict) { | |
if(charDict[ch] % 2 != 0) { | |
if(odd_cnt > 0) | |
charDict[ch] = charDict[ch] - 1; | |
else | |
odd_cnt++; | |
} | |
} | |
for(var ch in charDict) { | |
if(charDict[ch] == 0) | |
delete charDict[ch]; | |
} | |
return charDict; | |
} | |
function createPallindrome(charDict) { | |
var halfpalli=""; | |
var pivot=""; | |
for(var ch in charDict) { | |
if(charDict[ch] % 2 == 0) { | |
var cl = charDict[ch]; | |
for(var i=0;i<cl/2;i++) { | |
halfpalli = halfpalli + ch; | |
} | |
} | |
else { | |
if(charDict[ch] == 1) { | |
pivot= ch; | |
} | |
else { | |
var cl = charDict[ch]; | |
for(var i=0;i<cl/2;i++) { | |
halfpalli = halfpalli + ch; | |
} | |
pivot = ch; | |
} | |
} | |
} | |
return halfpalli + pivot + halfpalli.split('').reverse().join('');; | |
} | |
function solution(str) { | |
return createPallindrome(parseAndDropChars(str)); | |
} | |
///Verification | |
console.log(solution("abc")); | |
console.log(solution("aabbcc")); | |
console.log(solution("abbaccd")); | |
console.log(solution("aba")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment