Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 모든 문자 교체 쿼리 후 회문 확인

<시간/>

세트 Q에 문자열과 일부 쿼리가 있다고 가정합니다. 각 쿼리에는 정수 i와 j 쌍이 포함되어 있습니다. 그리고 다른 캐릭터 c. 인덱스 i와 j의 문자를 새 문자 c로 바꿔야 합니다. 그리고 문자열이 회문인지 아닌지 알려주세요. 문자열이 "AXCDCMP"와 같다고 가정하고 (1, 5, B)와 같은 쿼리를 사용하면 문자열은 "ABCDCBP"가 되고 (0, 6, A)와 같은 다른 쿼리는 "ABCDCBA"가 됩니다. ", 회문입니다.

인덱스 i, j를 사용하여 하나의 쿼리를 만든 다음 문자열에서 인덱스 i, j에 있는 문자를 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