Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created May 21, 2019 01:41
Show Gist options
  • Save anushshukla/4445fd831ad2ac9e1f80b96436e5baa8 to your computer and use it in GitHub Desktop.
Save anushshukla/4445fd831ad2ac9e1f80b96436e5baa8 to your computer and use it in GitHub Desktop.
Check if string is palindrome if 1 or 2 characters can be removed from anywhere
const handlePrintAfterCharRemoval = (result, char) => {
switch (result) {
case 'palindrome': return char;
case 'not possible': return result;
default :
if (result.length === 1) {
return `${result}${char}`;
}
return ''; // implies that function should continue to try other ways to check the plaindrome
}
}
function PalindromeCreator(str, index = 0, misMatchStr = '') {
// code goes here
const strLen = str.length - index - 1;
let revisedMisMatchStr = misMatchStr;
const currChar = str[index];
const reverseChar = str[strLen];
const reachedHalfWay = Math.round(str.length / 2) === index;
if (currChar !== reverseChar) {
const removeCurrChar = str.slice(0, index) + str.slice(index + 1, str.length);
const resultAfterCurrCharRemoval = handlePrintAfterCharRemoval(PalindromeCreator(removeCurrChar), currChar);
if (resultAfterCurrCharRemoval) {
return resultAfterCurrCharRemoval;
}
const removeLastChar = str.slice(0, strLen) + str.slice(strLen + 1, str.length);
const resultAfterLastCharRemoval = handlePrintAfterCharRemoval(PalindromeCreator(removeCurrChar), reverseChar);
if (resultAfterLastCharRemoval) {
return resultAfterCurrCharRemoval;
}
revisedMisMatchStr += `${currChar}${reverseChar}`;
}
if (revisedMisMatchStr.length > 2) {
return 'not possible';
}
if (reachedHalfWay) {
return misMatchStr ? misMatchStr : 'palindrome';
}
return PalindromeCreator(str, index + 1, revisedMisMatchStr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment