LeetCode-680-验证回文字符串 Ⅱ

给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

image.png

解题思路:

  1. 判断是否回文字符串:isPalindrome = lambda x: x==x[::-1],即将字符串x倒置,还和原来的一样;
  2. 如何判断删除一个字符后还是回文字符串?假设字符串s='abccbca',当用双指针从两端向中间游走,如果两指针所指字符不相等,考虑删除其中之一,再判断是否回文字符串。
  3. 该例中当left=1和right=5时,删除其中之一再判断,只需判断left和right之间的字符串是否回文,生成的新的两个字符串分别为删除右边字符:s[left:right],删除左边字符:s[left+1:right+1]

Python3代码:

class Solution:
    def validPalindrome(self, s: str) -> bool:
        left = 0
        right = len(s)-1
        isPalindrome = lambda x : x == x[::-1]

        while left<=right:
            if s[left] != s[right]:
                return isPalindrome(s[left:right]) or isPalindrome(s[left+1:right+1])
            else:
                left+=1
                right-=1
        return True 

你可能感兴趣的:(LeetCode-680-验证回文字符串 Ⅱ)