680. Valid Palindrome II

问题
Given a string s, return true if the s can be palindrome after deleting at most one character from it.

双指针,字符串两边对比。
如果两边字符不相等,则更新两边指针,并分别传入辅助方法再次对比。
两个结果有一个是true则返回true。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public boolean validPalindrome(String s) {
int left = 0;
int right = s.length() - 1;

while (left < right){
if (s.charAt(left) == s.charAt(right) ){
left++;
right--;
}
else{
return ( checkPalindrome(s, left+1, right) || checkPalindrome(s, left, right-1));
}
}
return true;
}
private boolean checkPalindrome(String s, int left, int right){
while (left < right){
if (s.charAt(left)==s.charAt(right)){
left++;
right--;
}
else{
return false;
}
}
return true;
}
}
Author

Xander

Posted on

2022-04-07

Updated on

2022-04-20

Licensed under

Comments