Easy
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.
这道题注意下时间复杂度,第一种做法tle了:大神给的提示:
一般做题多了会有感觉,比如
n^3 ---->10^2- 10^3,
n^2 ---->10^3- 10^4,
nlogn ----> 10^4- 10^6,
n ---->10^6- 10^7
class Solution {
//Construct all possible String that deleted one character from original string s
//then find out if there exist one palindrome
public boolean validPalindrome(String s) {
if (s == null || s.length() == 0){
return true;
}
int l = 0;
int r = s.length() - 1;
int count1 = 0;
int count2 = 0;
while (l < r){
if (s.charAt(l) != s.charAt(r)){
l++;
count1++;
} else {
l++;
r--;
}
}
l = 0;
r = s.length() - 1;
while (l < r){
if (s.charAt(l) != s.charAt(r)){
r--;
count2++;
} else {
l++;
r--;
}
}
return (count1 < 2 || count2 < 2);
}
}
A better way:
这种做法直接用Two Pointers, 遇到charAt(l) != chatAt(r)的时候,再看看分别去掉左边当前char的字符串和去掉右边当前char字符串的是不是回文就行了。
class Solution {
//Construct all possible String that deleted one character from original string s
//then find out if there exist one palindrome
public boolean validPalindrome(String s) {
if (s == null || s.length() == 0){
return true;
}
int l = 0;
int r = s.length() - 1;
while (l < r){
if (s.charAt(l) != s.charAt(r)){
return (isValidPalindrome(s, l + 1, r) || isValidPalindrome(s, l, r - 1));
} else {
l++;
r--;
}
}
return true;
}
public boolean isValidPalindrome(String s, int l, int r){
while (l < r){
if (s.charAt(l) != s.charAt(r)){
return false;
} else {
l++;
r--;
}
}
return true;
}
}