题目
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
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
我的想法
brute force:
O(n2)毫无悬念的超时了
class Solution {
public boolean validPalindrome(String s) {
if(s == null || s.length() == 0) {
return false;
}
for(int i = 0; i < s.length(); i++) {
String str = s.substring(0, i) + s.substring(i+1, s.length());
int head = 0, end = str.length() - 1;
while(head < end) {
if(str.charAt(head) != str.charAt(end)) {
break;
}
head++;
end--;
}
if(head >= end) {
return true;
}
}
return false;
}
}
two pointer:
对于删除掉一个元素可以变成回文串的字符串,如"ascbbcesa",在不相等的地方,要不然左边往前推一个要不然右边往前推一个,可以使得接下来的元素接着相等
class Solution {
public boolean validPalindrome(String s) {
if(s == null || s.length() == 0) {
return false;
}
int head = 0, end = s.length() - 1;
while(head < end) {
if(s.charAt(head) != s.charAt(end)) {
boolean left = helper(s, head + 1, end);
boolean right = helper(s, head, end - 1);
return (left || right);
}
head++;
end--;
}
return true;
}
private boolean helper(String s, int head, int end) {
while(head < end) {
if(s.charAt(head) != s.charAt(end)) {
return false;
}
head++;
end--;
}
return true;
}
}