Move two pointers inward. At the first mismatch, test the two possible single-character skips; no later branching is necessary.
Complexity
O(n) time and O(1) extra space.
Check whether a string can become a palindrome after deleting at most one character.
Move two pointers inward. At the first mismatch, test the two possible single-character skips; no later branching is necessary.
O(n) time and O(1) extra space.
package main
func validPalindrome(s string) bool {
isPalindrome := func(left int, right int) bool {
for left < right {
if s[left] != s[right] {
return false
}
left++
right--
}
return true
}
left, right := 0, len(s)-1
for left < right {
if s[left] != s[right] {
return isPalindrome(left+1, right) || isPalindrome(left, right-1)
}
left++
right--
}
return true
}
class Solution:
def validPalindrome(self, s: str) -> bool:
def is_palindrome(left: int, right: int) -> bool:
while left < right:
if s[left] != s[right]: return False
left, right = left + 1, right - 1
return True
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return is_palindrome(left + 1, right) or is_palindrome(left, right - 1)
left, right = left + 1, right - 1
return True
function validPalindrome(s: string): boolean {
const isPalindrome = (left: number, right: number): boolean => {
while (left < right) { if (s[left] !== s[right]) return false; left += 1; right -= 1; }
return true;
};
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) return isPalindrome(left + 1, right) || isPalindrome(left, right - 1);
left += 1; right -= 1;
}
return true;
}