Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra palindrome sau mỗi truy vấn thay thế ký tự trong C++


Cho một chuỗi và tập truy vấn Q. Mỗi truy vấn chứa cặp chỉ số i, j và ký tự c. Thay thế ký tự tại i và j bằng c, sau đó kiểm tra chuỗi có phải palindrome hay không. Ví dụ chuỗi "AXCDCMP", truy vấn (1,5,'B') → "ABCDCBP", truy vấn (0,6,'A') → "ABCDCBA" (palindrome).

Ví dụ

#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);
}

Kết quả

ABCDCBP is not Palindrome ABCDCBA is Palindrome