본문 바로가기

Competition/codeforces

Educational Codeforces Round 56 (Rated for Div. 2) B. Letters Rearranging

B. Letters Rearranging

https://codeforces.com/problemset/problem/1093/B


회문인지 아닌지 검사하는 문제이다.

만약 회문이라면 문자열을 바꿔 회문이 아니게 만들 수 있으면 된다.

어떤 문자열을 바꿔도 회문이 된다면 -1을 출력한다.


1. 문자열의 양 끝에서 같은 문자인지 검사하다가 다르면 string을 그대로 출력한다.

2. 회문이라면, 가운데 글자와 다른 글자를 하나 찾아서 바꾼다. 그리고 출력한다.

3. 회문이고, 모든 글자가 같다면 -1을 출력한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>
using namespace std;
 
int n;
string s;
int main() {
    ios::sync_with_stdio(0);
    cin.tie(NULL); cout.tie(NULL);
    cin >> n;
    while (n--) {
        cin >> s;
        bool pel = true;
        int len = s.length();
        for (int i = 0; i < len / 2; i++) {
            if (s[i] != s[len - 1 - i]) {
                pel = false;
                break;
            }
        }
        if (!pel) {
            cout << s << '\n';
        }
        else {
            for (int i = 0; i < len / 2; i++) {
                if (s[i] != s[len / 2]) {
                    swap(s[i], s[len / 2]);
                    pel = false;
                    break;
                }
            }
            if (!pel) {
                cout << s << '\n';
            }
            else cout << "-1\n";
        }
    }
    return 0;
}
cs