Python Leetcode(680.验证回文字符串)

    xiaoxiao2023-10-16  28

    Python Leetcode(680.验证回文字符串)

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

    示例 1:

    输入: “aba” 输出: True

    示例 2:

    输入: “abca” 输出: True 解释: 你可以删除c字符。

    注意:

    字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。

    Solution:(双指针是已有的思路,删除字符比较是看了题解之后的思路。设置头尾指针,因为只有一次修改字符的机会,当指针对应的两个元素不相等时,对指针内部的字符串左移一个或者右移一个进行回文串判断就可以了。)

    class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ if s == s[: : -1]: return True head, tail = 0, len(s)-1 while head < tail: if s[head] == s[tail]: head += 1 tail -= 1 else: a = s[head: tail] b = s[head+1: tail+1] return a == a[: : -1] or b == b[: : -1] solution = Solution() print(solution.validPalindrome('abcdca')) True
    最新回复(0)