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;
}
}