680. Valid Palindrome II*
https://leetcode.com/problems/valid-palindrome-ii/
题目描述
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.
C++ 实现 1
当 s[i] != s[j]
的时候, 要么删除 s[i]
, 要么删除 s[j]
. 只要有一种情况能得到 Palindrome 字符串, 那么就可以返回 true
.
class Solution {
private:
// 用 dir 表示移动方向, +1 表示 ++i, 相当于删除 s[i]
// -1 表示 --j, 相当于删除 s[j]
// 使用 count 记录删除次数, 最多一次
bool isPalindrome(const string &s, int dir) {
int i = 0, j = s.size() - 1;
int count = 0;
while (i <= j) {
if (s[i] != s[j]) {
if (dir == 1) ++ i;
else if (dir == -1) -- j;
++ count;
if (count > 1) return false;
continue;
}
++ i;
-- j;
}
return true;
}
public:
bool validPalindrome(string s) {
auto a = isPalindrome(s, 1); // 删除 s[i]
auto b = isPalindrome(s, -1); // 删除 s[j]
return a || b;
}
};
C++ 实现 2
LeetCode 的 Submission 中的一种做法. 用 s.erase(i, 1)
直接删除 s[i]
… 其中判断某字符是否为回文串的代码可以学习, 因为我一直用对撞指针来判断回文串. 这里直接用 reverse
后的字符串和原字符串相同.
发现还是用对撞指针好… 这里要额外分配一个 string.
bool valid(string s) {
string tmp = s;
std::reverse(tmp.begin(), tmp.end());
if( tmp == s ) return true;
else return false;
}
下面是最后的实现代码:
class Solution {
public:
bool validPalindrome(string s) {
int i = 0, j = s.length()-1;
string tmp = s;
while( i < j ){
if( s[i] == s[j] ) ++i, --j;
else{
string s1 = s.erase(i,1);
string s2 = tmp.erase(j,1);
if( valid(s1) ) return true;
else if( valid(s2)) return true;
else return false;
}
}
return true;
}
bool valid(string s){
string tmp = s;
std::reverse(tmp.begin(), tmp.end());
if( tmp == s ) return true;
else return false;
}
};