lc680. Valid Palindrome II

180 阅读1分钟

680. Valid Palindrome II

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.

思路:头head尾tail逐个字符比较,如果有不相等的字符,分两种情况, 跳过左边的一个字符,遍历其他字符,如果都相等,True,如果不相等,跳过右边的,遍历其他字符,如果都相等,True,否则False

代码:python3

class Solution:
   def validPalindrome(self, s: str) -> bool:
       l=0
       r=len(s)-1
       while l<r:
           if s[l]==s[r]:
               l+=1
               r-=1
           else:
               left=l
               right=r-1
               while left<=right:
                   if s[left] != s[right]:
                       break;
                   left+=1
                   right-=1
                   if left>=right:
                       return True
               l+=1
               while l<=r:
                   if s[l] != s[r]:
                       break;
                   l+=1
                   r-=1
                   if l>=r:
                       return True
               return False
       return True