[leetcode] problem 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

No.1

Input: “aba”

Output: True

No.2

Input: “abca”

Output: True

Explanation: You could delete the character ‘c’.

Note

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public boolean (String s) {
int left = 0;
int right = s.length() - 1;

while (left < right) {
if (s.charAt(left) != s.charAt(right))
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);

left++;
right--;
}

return true;
}

private boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right))
return false;

left++;
right--;
}

return true;
}