lintcode练习- 891. Valid Palindrome II

891. Valid Palindrome II

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

样例

Given s = "aba" return true
Given s = "abca" return true // delete c

注意事项

The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

解题思路:

通过下标进行处理,如果不相等,则忽略该下标,应为只能删除一个值,如果结果依然不相等,则该字符串无法构成回文。

class Solution:
    """
    @param s: a string
    @return: nothing
    """
    def validPalindrome(self, s):
        # Write your code here
        left, right = 0, len(s)-1
        while left < right:
            if s[left] != s[right]:
                return self.isPalindrome(s, left+1, right) or self.isPalindrome(s, left, right-1)
            left += 1
            right -= 1
        
        return True
            
    
    def isPalindrome(self, s, start, end):
        while start < end:
            if s[start]!=s[end]:
                return False
            
            start += 1
            end -= 1
        
        return True

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81805995