[ 백준 ] 17609 / 회문

金弘均·2021년 9월 16일
0

Baekjoon Online Judge

목록 보기
166/228
post-thumbnail

# Appreciation

/*
 * Problem :: 17609 / 회문
 *
 * Kind :: Math
 *
 * Insight
 * - 유사회문 = 한 문자를 삭제하여 회문으로 만들 수 있는 문자열
 *   + 주어진 문자열이 회문인지 판별하는 중, 검사하는 앞글자와 뒷글자가 다르면
 *     그 앞글자를 제외하고 남은 검사해야될 문자열이 회문이거나
 *     그 뒷글자를 제외하고 남은 검사해야될 문자열이 회문이면
 *     유사회문이다
 */

# Code

//
//  BOJ
//  ver.C++
//
//  Created by GGlifer
//
//  Open Source

#include <iostream>
#include <algorithm>

using namespace std;

#define endl '\n'

// Set up : Global Variables
/* None */

// Set up : Functions Declaration
bool isPalindrome(string s);
bool isPseudoPalindrome(string s);


int main()
{
    // Set up : I/O
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // Set up : Input
    int T; cin >> T;

    while (T--) {
        string str; cin >> str;

        // Process
        // Control : Output
        /* 회문이면 0, 유사회문이면 1, 둘 모두 아니면 0 을 출력 */
        cout << (isPalindrome(str) ? 0 : isPseudoPalindrome(str) ? 1 : 2) << endl;
    }
}

// Helper Functions
bool isPalindrome(string s)
/* 주어진 문자열 s 가 회문이면 true 를 반환, 그 외 false 를 반환 */
/* 주어진 문자열을 복사하고 뒤집은 문자열 r 을 만든 후, s == r 의 여부로 회문을 판별 */
{
    string r = s;
    reverse(r.begin(), r.end());
    return s == r;
}

bool isPseudoPalindrome(string s)
/* 주어진 문자열 s 가 유사회문이면 true 를 반환, 그 외 false 를 반환 */
{
    int N = s.length();
    for (int i=0; i<N/2; i++) {
        if (s[i] != s[N-1-i]) { /* 검사하는 앞글자와 뒷글자가 다르면 */
            string s1 = s.substr(i+1, N-1-2*i); /* 그 앞글자 제외 남은 문자열 */
            string s2 = s.substr(i, N-1-2*i); /* 그 뒷글자 제외 남은 문자열 */
            /* 두 문자열 중 하나가 회문이면 유사회문임 */
            return isPalindrome(s1) || isPalindrome(s2);
        }
    }
    return false;
}
profile
이런 미친 게임을 봤나! - 옥냥이

0개의 댓글