[leetcode] 680. Valid Palindrome II @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88955337

原题

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’.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

解法

双指针法. 左右指针往中间刷, 遇到不同的两个字母, 有两种可能的删除法: 删除左边的字符, 删除右边的字符, 检查这两种方法有没有是回文即可. 以’dceabacd’为例, 当走到’eaba’时, 发现两个指针指向不同的字符, 一种方法是’eab’, 一种方法是’aba’.

代码

class Solution(object):
    def validPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left, right = 0, len(s)-1
        while left < right:
            if s[left] != s[right]:
                # delete left
                one = s[left+1:right+1]
                # delete right
                two = s[left:right]
                return one == one[::-1] or two == two[::-1]
            left += 1
            right -= 1
        return True

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88955337
今日推荐