考虑我们有一个字符串和集合Q中的一些查询。每个查询都包含一对整数i和j。和另一个字符c。我们必须用新字符c替换索引i和j处的字符。并告诉该字符串是否是回文。假设一个字符串像“ AXCDCMP”,如果我们使用一个查询,如(1,5,B),则该字符串将为“ ABCDCBP”,然后使用另一个查询,如(0,6,A),则为“ ABCDCBA” ”,这是回文。
我们必须使用索引i,j创建一个查询,然后用c替换字符串中索引i,j处的字符。
#include <iostream>
using namespace std;
class Query{
public:
int i, j;
char c;
Query(int i, int j, char c){
this->i = i;
this->j = j;
this->c = c;
}
};
bool isPalindrome(string str){
int n = str.length();
for (int i = 0; i < n/2 ; i++)
if (str[i] != str[n-1-i])
return false;
return true;
}
bool palindromeAfterQuerying(string str, Query q[], int n){
for(int i = 0; i<n; i++){
str[q[i].i] = q[i].c;
str[q[i].j] = q[i].c;
if(isPalindrome(str)){
cout << str << " is Palindrome"<< endl;
}else{
cout << str << " is not Palindrome"<< endl;
}
}
}
int main() {
Query q[] = {{1, 5, 'B'}, {0, 6, 'A'}};
int n = 2;
string str = "AXCDCMP";
palindromeAfterQuerying(str, q, n);
}输出结果
ABCDCBP is not Palindrome ABCDCBA is Palindrome