Question 9 Valid Palindrome II
// Some code
```java
/*
Clarification & Assumption
- string: all characters
- output: valid defined validPalindrome, could delete one characters
High Level
- two pointers from left& right
- two pointers: find their characters if they are same
Middle Level
- two pointers from left & right
- if they are same? left++, right--
- if they are not same? two possible options
- either check left++ with right
- or check right-- with left;
TC & SC: O(n), O(1)
*/
class Solution {
public boolean validPalindrome(String s) {
// sanity check
//
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) == s.charAt(right)) {
left++;
right--;
}
else {
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
}
return true;
}
private boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
```
Last updated