Leetcode-680(回文字符串)

时间:2020-04-09 12:48:40   收藏:0   阅读:74

1.题目

可以删除一个字符,判断是否能构成回文字符串。:

Input: "abca"
Output: True
Explanation: You could delete the character ‘c‘.

2.代码实现:

class Solution(object):
    def validPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        p1, p2 = 0, len(s) - 1
        while p1 < p2:
            if s[p1] != s[p2]:
                # 舍弃左字符
                a = s[p1 + 1: p2 + 1]
                # 舍弃右字符
                b = s[p1:p2]
                # 判断是否为回文字符串
                return a[::-1] == a or b[::-1] == b
            p1 += 1
            p2 -= 1
        return True

 

3.注意事项:

1.切片的使用 左闭后开,也就是说右边的值取不到

2.这里用while判断,是因为无法确定循环的次数,return都是结束循环的条件

3.回文数 a=a[::-1]

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!