- tags: String,Two Pointers,LeetCode101
Two pointers move inwards, when we meet two different characters:
- Remove left character to see if the remains string still satisfied a valid palindrome.
- Remove right character to see if the remains string still satisfied a valid palindrome.
Returns true if either one above two is true.
class Solution {
public:
bool validPalindrome(string s) {
for (int i = 0, j = s.size() -1; i < j; i++,j--) {
if (s[i] != s[j]) {
// remove left
auto left = isPalindrome(s, i + 1, j);
// remove right
auto right = isPalindrome(s, i, j - 1);
// return at here as we have traveled the string in the
// invocation of isPalindrome.
return right || left;
}
}
return true;
}
private:
bool isPalindrome(string & s, int i, int j) {
for (; i < j; i++,j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
};