Description:
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.
题意:判断一个字符串是否为回文,最多允许删除字符串中的一个字符;
解法:对于字符串来说,如果去掉首尾已经相等的字符得到的字符串为s;即s[i] != s[j](0<=i…<= j < s.length());那么我们就只需要判断字符串i与j之间的是否为回文,因为允许删除一个字符,所以需要判断s.substring(i, j)和s.substring(i + 1, j + 1)是否为回文;
Java
class Solution {
public boolean validPalindrome(String s) {
int begin = 0;
int end = s.length() - 1;
while (begin < s.length() && end >= 0 && s.charAt(begin) == s.charAt(end)) {
begin++;
end--;
}
return isPalindrome(s, begin, end - 1) || isPalindrome(s, begin + 1, end);
}
//判断字符串是否是回文
private boolean isPalindrome(String S, int begin, int end) {
while (begin < end) {
if (S.charAt(begin) != S.charAt(end)) return false;
begin++;
end--;
}
return true;
}
}