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: True
Example 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.
eg:
a b b c d c b a
0 1 2 3 4 5 6 7
设置两根指针,left 和right 分别指向头尾。
当left == 2 && right == 5 的时候,他们指向的字符不一样,可以被分为两种情况:
1. 删除s[left],判断s[3] - s[5]是不是回文
2. 删除s[right], 判断s[2] - s[4]是不是回文
根据上述推断可以写出代码:
class Solution {
public:
bool isPalindrome(string s, int left, int right) {
while (left < right) {
if (s[left] == s[right]) {
left++;
right--;
} else {
return false;
}
}
return true;
}
bool validPalindrome(string s) {
if (s.length() < 2) {
return true;
}
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s[left] != s[right]) {
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
left++;
right--;
}
return true;
}
};