LeetCode 680. Valid Palindrome II
原题链接在这里:https://leetcode.com/problems/valid-palindrome-ii/description/
题目:
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.
题解:
当出现错位时,或左或右向内移动一位.
Time Complexity: O(s.length()). Space: O(1).
AC Java:
1 class Solution { 2 public boolean validPalindrome(String s) { 3 int l = 0; int r = s.length()-1; 4 while(l<r){ 5 if(s.charAt(l) != s.charAt(r)){ 6 return isPalindrome(s, l+1, r) || isPalindrome(s, l, r-1); 7 } 8 l++; 9 r--; 10 } 11 return true; 12 } 13 14 private boolean isPalindrome(String s, int l, int r){ 15 while(l<r){ 16 if(s.charAt(l) != s.charAt(r)){ 17 return false; 18 } 19 l++; 20 r--; 21 } 22 return true; 23 } 24 }
AC Python:
1 class Solution: 2 def validPalindrome(self, s: str) -> bool: 3 if not s: 4 return True 5 6 i, j = 0, len(s) - 1 7 while i < j: 8 if s[i] != s[j]: 9 return self.isPal(s, i + 1, j) or self.isPal(s, i, j - 1) 10 i+=1 11 j-=1 12 return True 13 14 def isPal(self, s, l, r): 15 while l < r: 16 if s[l] != s[r]: 17 return False 18 l += 1 19 r -= 1 20 return True