Last active
February 11, 2021 17:57
-
-
Save keune/9997278 to your computer and use it in GitHub Desktop.
Remove a letter to make a palindrome
This file contains hidden or 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
function tryToGetPalinDrome(str) { | |
// Returns -2 if the given word is already a palindrome | |
// Returns -1 if it is impossible to make a palindrome by removing one letter from the given word | |
// Returns a positive integer that shows the position of the character to remove from the word to make a palindrome | |
if(str === reverse(str)) return -2; // already a palindrome | |
var strlen = str.length; | |
for(var i=0; i<strlen; i++) { | |
var partial = str.substring(0, i) + str.substring(i+1, strlen); | |
var reversed = reverse(partial); | |
if(partial === reversed) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
function reverse(str) { | |
var newStr = ''; | |
for(var i=str.length; i>=0; i--) { | |
newStr += str.charAt(i); | |
} | |
return newStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment