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.
/*
* @lc app=leetcode id=680 lang=cpp
*
* [680] Valid Palindrome II
*/
// @lc code=start
class Solution {
public:
bool validPalindrome(string s) {
const auto palind = [&](int l, int r) {
while (l < r) {
if (s[l] != s[r]) return false;
else {
++l;
--r;
}
}
return true;
};
for (int l = 0, r = s.length() - 1; l < r; ++l, --r) {
if (s[l] != s[r]) {
return palind(l + 1, r) || palind(l, r - 1);
}
}
return true;
}
};
// @lc code=end
class Solution {
private boolean isPalin(String s, int start, int end) {
for (; start < end; start++, end--) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
}
return true;
}
public boolean validPalindrome(String s) {
for (int l = 0, r = s.length() - 1; l < r; l++, r--) {
if (s.charAt(l) == s.charAt(r)) {
continue;
} else {
return isPalin(s, l + 1, r) || isPalin(s, l, r - 1);
}
}
return true;
}
}
时间O(N).