[leetcode] 680. Valid Palindrome II @ python

原题

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值