Title:Valid Palindrome II 680
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/valid-palindrome-ii/
1. 见代码注释
时间复杂度:O(n),虽然是嵌套循环,但是只是遍历了一遍。
空间复杂度:O(1),没有申请额外空间。
/**
* 删除一个字符(左或者右)
* @param s
* @return
*/
public static boolean validPalindrome(String s) {
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return isPalindrome(s, start + 1, end) || isPalindrome(s, start, end - 1);
}
else {
start++;
end--;
}
}
return true;
}
/**
* 删除一个字符后,判断是否为回文字符串
* @param s
* @param start
* @param end
* @return
*/
private static boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
else {
start++;
end--;
}
}
return true;
}