680.Valid Palindrome II
Easy
5834310Add to ListShare
Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
这是一个双指针问题,但是要注意删除后面或者前面的数有两个选择,会出现不该删除该字母但是结果旁边,例如,我下面这段代码就是这样的问题:
class Solution {
public boolean validPalindrome(String s) {
int high = s.length()-1, low = 0;
boolean t = true, isPalindrome = true;
while (low < high){
if (s.charAt(low) == s.charAt(high)) {low++;high--;continue;}
else if (t && (s.charAt(low) == s.charAt(high-1))) {low ++; high = high-2; t = false;continue;}
else if (t && (s.charAt(low+1) == s.charAt(high))) {low = low+2; high--; t = false;continue;}
else {isPalindrome = false; break;}
}
return isPalindrome;
}
}
改过来之后,再定义一个函数来判断
class Solution {
public boolean validPalindrome(String s) {
for (int i = 0, j = s.length()-1; i<j; i++,j--){
if (s.charAt(i) != s.charAt(j)){
return isPalindrome(s,i,j-1) || isPalindrome(s,i+1,j);
}
}
return true;
}
private static boolean isPalindrome(String s, int i,int j){
while(i<j){
if (s.charAt(i++)!=s.charAt(j--)) return false;
}
return true;
}
}
大公搞成了!!