Created
May 21, 2019 01:41
-
-
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
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
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