We are required to write a JavaScript function that takes in a string as the first and the only argument.
The task of our function is to check whether we can make that string a palindrome string by deleting at most one character from the string. If we can do so, the function should return true, false otherwise.
For example −
If the input string is −
const str = 'kjlk';
Then the output should be −
const output = true;
because by deleting 'l' from the string, only 'kjk' will be left which is a palindrome string.
Example
The code for this will be −
const str = 'kjlk'; const isPalindrome = (str = '', start, end) => { while (start < end) { if (str[start] != str[end]) { return false; }; start ++; end --; }; return true; }; const canMakePalindrome = (str = '') => { let left = 0, right = str.length - 1; while (left < right - 1) { if (str[left] !== str[right]) { if (isPalindrome(str, left, right - 1)) { return true; }; if (isPalindrome(str, left + 1, right)) { return true; }; return false; }else { left ++; right --; }; }; return true; } console.log(canMakePalindrome(str));
Output
And the output in the console will be −
true