Если задана строка s, проверьте, можно ли сделать ее палиндромом, удалив по НАИБОЛЕЕ один символ (то есть, допустимо нулевое удаление). Строка s будет содержать <50 000 строчных букв алфавита. </p>
Код, который я написал ниже, прошел 458/460 тестовых случаев, и он застрял на одном из них без видимой причины, возвращая false вместо true. Логика алгоритма проста, и я пробовал перемещать условные выражения, но, похоже, ничего не изменилось.
class Solution {
public:
bool ispalindrome; //holds result
bool validPalindrome(string s) {
bool candelete = true; //allows one delete
ispalindrome = true; //initial condition
int lcursor = 0;
int rcursor = s.length() - 1;
while(lcursor < rcursor && ispalindrome){
//if cursor points at different letters
if(s[lcursor] != s[rcursor]){
// if delete is still allowed and delete works
if(s[lcursor + 1] == s[rcursor] && candelete){
lcursor++;
candelete = false;
} else if (s[lcursor] == s[rcursor - 1] && candelete){
rcursor--;
candelete = false;
} else {
ispalindrome = false;
}
}
lcursor++;
rcursor--;
}
return ispalindrome;
}
};
Тестовый случай, который отключает это решение, выглядит следующим образом:
aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga
Тестирование кода с помощью этого теста:
#include <iostream>
using std::string;
// class Solution { ... etc., from above
int main() {
string s = "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga";
std::cout << Solution().validPalindrome(s) << std::endl;
};