680. Valid Palindrome II
Easy
5621303Add to ListShare
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
Example 2:
Input: s = "abca" Output: true Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc" Output: false
Constraints:
1 <= s.length <= 105
s
consists of lowercase English letters.
运行时间似乎有点长
class Solution:
def validPalindrome(self, s: str) -> bool:
"""
assert Solution().validPalindrome("aba")
assert Solution().validPalindrome("abca")
assert not Solution().validPalindrome("abc")
解体思路:回文判断,有一次删除机会,使用的时候分成2种情况继续
时间复杂度:O(n)
"""
def validPalindromeImpl(self, s: str, l: int, r: int, delete: bool) -> bool:
if l >= r:
return True
if s[l] == s[r]:
return validPalindromeImpl(self, s, l + 1, r - 1, delete)
if delete:
return validPalindromeImpl(self, s, l + 1, r, False) or validPalindromeImpl(self, s, l, r - 1, False)
return False
if len(s) == 1:
return True
return validPalindromeImpl(self, s, 0, len(s) - 1, True)