Revision 2·24 Sept
Valid Palindrome II
tl;dr
Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it.
full write-up
Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it.
Constraints
- 1 ≤
string.length≤ 10³ - The string only consists of English letters.
Examples
Example 1
Input: "ABCEBA"
Output: TRUE
Example 2
Input: "RACEACAT"
Output: FALSE
Example 3
Input: "DEEAD"
Output: TRUE
Solution To solve this, I'll reuse Previously generated IsPalindrome function. We'll add a condition before rejecting it check for substring start+1 and end-1 if any of them is palindrome our string is palindrome
function isPalindrome(str) {
let start = 0;
let end = str.length - 1;
while (start <= end) {
if (str[start] !== str[end]) {
return false;
}
start++;
end--;
}
return true;
}
function validPalindromII(str) {
let start = 0;
let end = str.length - 1;
while (start <= end) {
if (str[start] !== str[end]) {
return (
isPalindrome(str.slice(start, end)) || // drop char at `end`
isPalindrome(str.slice(start + 1, end + 1)) // drop char at `start`
);
}
start++;
end--;
}
return true;
}
console.log(validPalindromII('DEEAD')); // true
console.log(validPalindromII('ABBAC')); // true
console.log(validPalindromII('ABCEBA')); // true
console.log(validPalindromII('RACEACAT')); // false