问题描述:
Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.
示例:
Input: "aba" Output: True
Input: "abca" Output: True Explanation: You could delete the character 'c'.
问题分析:
题目中说最多除去一个字符,使得剩余的字符能够组成回文串。我们可以根据回文串的性质,使用双指针,两段同时比较,若有不相同的则计数器加一,若计数器的值大于1,我们就可以认定该字符串不能满足题意。
过程详见代码:
class Solution {
public:
bool validPalindrome(string s) {
int i = 0, j = s.length() - 1, count = 0;
int flag = 0;
while (i < j)
{
if (s[i] == s[j])
{
i++;
j--;
}
else
{
count++;
if (count > 1) return false;
if (s[i + 1] != s[j] && s[i] != s[j - 1]) return false;
if (s[i + 1] == s[j])
{
if (j > i + 2 && s[i + 2] != s[j - 1]) flag = 1;
if (!flag)
{
i++;
continue;
}
}
j--;
flag = 0;
}
}
return true;
}
};