Leetcode 680. Valid Palindrome II
Given a string s
, return true
if the s
can be a palindrome after deleting at most one character from it.
s
will have at least one character.s
contain?
s
will consist only of lowercase English letters.To determine if a string can be a palindrome after deleting at most one character, we can use a two-pointer approach:
left
) and one at the end (right
) of the string.left
and right
pointers.
left
pointer to the right and the right
pointer to the left.left
or right
pointer and check if the remaining substring (excluding the character) is a palindrome.To check if a substring is a palindrome, you can write a helper function that performs this check by using a similar two-pointer technique.
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool isPalindrome(const string& s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
bool validPalindrome(string s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
if (s[left] == s[right]) {
left++;
right--;
} else {
// Try removing either the left or the right character
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
}
return true;
}
};
// Example usage
int main() {
Solution solution;
string s = "abca";
if (solution.validPalindrome(s)) {
cout << "The string can be a palindrome after deleting at most one character." << endl;
} else {
cout << "The string cannot be a palindrome after deleting at most one character." << endl;
}
return 0;
}
O(n)
).O(n)
).O(n)
+ O(n)
, which simplifies to O(n)
overall.O(1)
since we only use a few extra variables for the pointers.Thus, the final time complexity is O(n)
and the space complexity is O(1)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?