Created
September 12, 2023 14:35
-
-
Save carefree-ladka/df4ab61d2df47ddb28c193d4945b4b5a to your computer and use it in GitHub Desktop.
Remove or add character to make a string 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 isPalindrome(str) { | |
| let low = 0; | |
| let high = str.length - 1; | |
| while (low < high) { | |
| if (str[low] !== str[high]) return false; | |
| low++; | |
| high--; | |
| } | |
| return true; | |
| } | |
| function makePalindrome(str) { | |
| for (let i = 0; i < str.length; i++) { | |
| const newStr = str.slice(0, i) + str.slice(i + 1); | |
| if (isPalindrome(newStr)) { | |
| return newStr; | |
| } | |
| } | |
| return "Cannot make a palindrome"; | |
| } | |
| console.log(makePalindrome("racecar")); //racecar | |
| console.log(makePalindrome("madamy")); //madam | |
| console.log(makePalindrome("mada")); //ada |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment