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.

Solution in python:

class Solution:
    def validPalindrome(self, s: str) -> bool:

        def ispalindrome(s):
            if len(s) <= 1:
                return True
            else:
                if s[0] == s[-1]:
                    return ispalindrome(s[1:-1])
                else:
                    return False

        i = 0
        j = len(s)-1
        while i < j:
            if s[i] == s[j]:
                i += 1
                j -= 1
            else:
                return ispalindrome(s[i+1:j+1]) or ispalindrome(s[i:j])
        return True
最后修改日期: 2021年3月26日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。