Check for Palindrome after every character replacement Query in C++
假设我们有一个字符串和一些查询集 Q。每个查询都包含一对整数 i 和 j。还有一个字符 c。我们必须将索引 i 和 j 处的字符替换为新字符 c。并判断该字符串是否为回文串。假设一个字符串类似于“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
广告