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
Constraints:
1 <= s.length <= 105
s
consists of lowercase English letters.
判断回文串,如果他不是的话,可以删掉任何一个字母,判断是否能成为回文串。想的时候想到了说双指针判断到两个指针不相同,然后就卡住了,不知道是该移左边的还是右边的,感觉写起来有点复杂。看了思路才发现直接可以写一个isPalindrome的helper,判断剩下还没走过的部分是否是回文串,因为外面走过的部分已经满足要求了,于是就看看去掉左指针或者去掉右指针之后还回不回文。代码很简单,直接copy了I的函数,看了解答大家直接写成了param为(i, j, s),确实就方便很多了。
class Solution {
public boolean validPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
} else {
return isPalindrome(s.substring(i, j)) || isPalindrome(s.substring(i + 1, j + 1));
}
}
return true;
}
private boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
} else {
return false;
}
}
return true;
}
}