DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Valid Palindrome II

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Example 1:

Input: s = "aba"
Output: true

/**
 * @param {string} s
 * @return {boolean}
 */
var validPalindrome = function (s) {
  let pstring = s;
  let start = 0;
  let end = s.length - 1;

  while (start <= end) {
    if (pstring[start] === pstring[end]) {
      start++;
      end--;
    } else {
      return (
        checkPalindrome(pstring, start + 1, end) ||
        checkPalindrome(pstring, start, end - 1)
      );
    }
  }
  return true;
};

const checkPalindrome = (s, i, j) => {
  let left = i;
  let right = j;
  while (left <= right) {
    if (s.charAt(left) == s.charAt(right)) {
      left++;
      right--;
    }else if (s.charAt(left) != s.charAt(right)) {
      return false;
    }
  }
  return true;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
santoshmore088 profile image
santosh more

br if possible try to add explanation also, it will benefit others also