LeetMotion
Given a string s, return true if the string can be a palindrome after deleting at most one character from it.
s consists of lowercase English letters.Try deleting each character from the string one at a time and check if the resulting string is a palindrome. Also check the original string itself.
i, build s[:i] + s[i+1:] (delete character at i).True.False.Why it's not optimal: O(n²) — each deletion creates an O(n) string, and we check up to n deletions. The two-pointer approach is O(n) by only checking the mismatch point.
def validPalindrome(s): def isPalin(t): return t == t[::-1] if isPalin(s): return True for i in range(len(s)): if isPalin(s[:i] + s[i+1:]): return True return False
Use two pointers from both ends. Match characters and move inward. On the first mismatch, we have one deletion budget — try skipping the left character or the right character and check if the remaining substring is a palindrome.
L=0, R=n-1. Move inward while characters match.isPalin(L+1, R) (skip left) and isPalin(L, R-1) (skip right).True.
Discussion
…