Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบ Palindrome หลัง Character Replacement Query ใน C++

พิจารณา String และ Queries ใน Set Q แต่ละ Query มี Pair (i, j) และ Character c ต้อง Replace Characters ที่ Index i และ j ด้วย c แล้วบอกว่า String เป็น Palindrome หรือไม่ ตัวอย่าง String "AXCDCMP" Query (1, 5, B) ได้ "ABCDCBP" Query (0, 6, A) ได้ "ABCDCBA" เป็น Palindrome

ตัวอย่างโค้ด C++

#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