leetcode solution 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 1:

1
2
Input: "aba"
Output: True

Example 2:

1
2
3
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.

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
class  {
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);
}
l++;
r--;
}
return true;
}
public boolean isPalindrome(String s, int l, int r){
while(l<r){
if(s.charAt(l) != s.charAt(r)){
return false;
}
else{
l++;
r--;
}
}
return true;
}
}
  • The basic idea is to compare the first ant the last character of string s . if s is a palindrome after remove one single letter. we can know that it can be seen as insert a letter into a palindrome.
  • so, we can consitently compare the first and the last letter of s , if they’re not the same, we judge the two substring which is the original string removing one of the ends letter.
    • aabbcaa : we consistently judge abbca -> bbc -> bb -> ba