原题链接在这里: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 }