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.
Solution:
class Solution {
public boolean validPalindrome(String s) {
char[] arr = s.toCharArray();
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (arr[left] != arr[right]) {
return isValid(Arrays.copyOfRange(arr, left + 1, right + 1)) || isValid(Arrays.copyOfRange(arr, left, right));
} else {
left ++;
right --;
}
}
return true;
}
private boolean isValid(char[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (arr[left ++] != arr[right --]) {
return false;
}
}
return true;
}
}