680. Valid Palindrome II (Easy)
Given a non-empty strings
, 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 1: Two Pointers O(n); O(1)
Use 2 pointers to traverse the string, one pointer starts from the string's left, the other starts from right.
During the traverse, left and right pointers move by one position each time. If left and right chars are not equal, check if the rest string without the left char or right char is a palindrome.
public boolean validPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
if (s.charAt(l) != s.charAt(r)) {
return isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1); //check the rest string directly
}
l++;
r--;
}
return true;
}
private boolean isPalindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
l++;
r--;
}
return true;
}