680. Valid Palindrome II

680. Valid Palindrome II

Description

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

Example 1:

1
2
Input: s = "aba"
Output: true

Example 2:

1
2
3
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.

Example 3:

1
2
Input: s = "abc"
Output: false

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.

Hints/Notes

Solution

Language: C++

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
30
class Solution {
public:
bool validPalindrome(string s) {
int left = 0, right = s.size() - 1;
bool deleted = false;
while (left < right) {
if (s[left] != s[right]) {
if (deleted) {
return false;
} else {
return check(s, left + 1, right) || check(s, left, right - 1);
}
}
left++;
right--;
}
return true;
}

bool check(string s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
};