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.
思路:暴力不过,改为递归,为了减小递归深度,先尽量用循环
class Solution {
public boolean validPalindrome(String s) {
char[] cs = s.toCharArray();
return validPalindrome(cs, 0, cs.length-1, 1);
}
private boolean validPalindrome(char[] cs, int i, int j, int cap) {
if(i<0||j<0||i>=cs.length||j>=cs.length) return false;
if(cap == -1) return false;
if(i >= j) return true;
while(i<j && cs[i]==cs[j]) {
i ++;
j --;
}
if(i >= j) return true;
return validPalindrome(cs, i+1, j, cap-1) || validPalindrome(cs, i, j-1, cap-1);
}
}