Problem
Given a strings, return true if the s can be palindrome after deleting at most one character from it.
Examples
Constraints
- 1 <= s.length <= 10^5
sconsists of lowercase English letters.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 680 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 680 # by problem number
lcpy gen -s valid_palindrome_ii # by problem name
s, return true if the s can be palindrome after deleting at most one character from it.
Input: s = "aba"
Output: true
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Input: s = "abc"
Output: false
s consists of lowercase English letters.class Solution:
# Time: O(n)
# Space: O(1)
def valid_palindrome(self, s: str) -> bool:
def is_palindrome(left: int, right: int) -> bool:
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
# Mismatch: try skipping either the left or the right character.
return is_palindrome(left + 1, right) or is_palindrome(left, right - 1)
left += 1
right -= 1
return True
| Time | Space |
|---|---|
| O(n) | O(1) |