[백준 알고리즘]/[C++]

백준 17609 회문 | C++

말하는펭귄 2021. 5. 19. 17:56
728x90
반응형

 

 

이번 포스팅은 백준 17609번 회문입니다.

아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.

https://www.acmicpc.net/problem/17609

 

17609번: 회문

각 문자열이 회문인지, 유사 회문인지, 둘 모두 해당되지 않는지를 판단하여 회문이면 0, 유사 회문이면 1, 둘 모두 아니면 2를 순서대로 한 줄에 하나씩 출력한다.

www.acmicpc.net

 

 

 

기본 알고리즘

두 포인터

 

 

 

전체 코드

 

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//백준17609 회문                                                            
#include <iostream>
#include <string>
using namespace std;
 
bool checkPalin(string str) {
    int s = 0;
    int e = str.length() - 1;
    while (s < e) {
        if (str[s] != str[e]) {
            return false;
        }
        else {
            s++;
            e--;
        }
    }
    return true;
}
 
void canPalin(string str) {
    int s = 0;
    int e = str.length() - 1;
    while (s < e) {
        if (str[s] != str[e]) {
            string original = str;
            string temp1 = str.erase(s,1);
            string temp2 = original.erase(e,1);
            /*cout << "temp1: " << temp1 << "\n";
            cout << "temp2: " << temp2 << "\n";*/
            if (checkPalin(temp1)) {
                //cout << "canPalin" << "\n";
                cout << 1 << "\n";
            }
            else if (checkPalin(temp2)) {
                //cout << "canPalin" << "\n";
                cout << 1 << "\n";
            }
            else {
                //cout << "notPalin" << "\n";
                cout << 2 << "\n";
            }
            return;
        }
        else {
            s++;
            e--;
        }
    }
}
 
int main() {
    int T;
    cin >> T;
 
    while (T--) {
        string str;
        cin >> str;
        if (checkPalin(str)) {
            //cout << "palin" << "\n";
            cout << 0 << "\n";
        }
        else {
            canPalin(str);
        }
    }
 
    return 0;
}
cs

 

 

 

 

728x90
반응형