[Easy] 680. Valid Palindrome II

Description

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Solution

遇到不一样。考虑删左边还是删右边

   def validPalindrome(self, s):
        left, right = self.two_pointer(s, 0, len(s) - 1)            
        if left >= right:
            return True
            
        return self.is_palindrome(s, left + 1, right) or self.is_palindrome(s, left, right - 1)

    def is_palindrome(self, s, left, right):
        left, right = self.two_pointer(s, left, right)
        return left >= right
        
    def two_pointer(self, s, left, right):
        while left < right:
            if s[left] != s[right]:
                return left, right
            left += 1
            right -= 1
        return left, right

你可能感兴趣的:([Easy] 680. Valid Palindrome II)