Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: “aba”
Output: TrueExample 2:
Input: “abca”
Output: True
Explanation: You could delete the character ‘c’.Note:
- The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
Runtime: 76 ms, faster than 94.71% of C++ online submissions for Valid Palindrome II.
Memory Usage: 1 MB, less than 77.08% of C++ online submissions for Valid Palindrome II.
class Solution {
public:
bool validPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) {
if (s[i] != s[j]) {
int i1 = i;
int j1 = j - 1;
int i2 = i + 1;
int j2 = j;
while (i1 < j1 && s[i1] == s[j1]) {
i1++;
j1--;
}
while (i2 < j2 && s[i2] == s[j2]) {
i2++;
j2--;
}
return i1 >= j1 || i2 >= j2;
}
}
return true;
}
};