[BOJ] 1213번 펠린드롬 만들기(C++) - 풀이 & 리팩토링

Alice·2023년 4월 7일
0

풀이 소요시간 : 35분

문제 풀이 접근은 성공했다.
홀수 갯수인 알파벳이 2개 이상인 경우 펠린드롬 형태를 만들 수 없다.
따라서 알파벳 갯수가 모두 짝수인 경우, 단 하나만 홀수인 경우가 존재한다.

각 알파벳의 갯수를 구하기 위해서 Map 을 사용했다. 어찌저찌 풀어서 정답으로 통과했지만 정석 풀이과정을 찾아보다가 배열로 카운팅을 하는것이 더욱 효과적이라 생각하여 다시 풀어보았다.

전체 코드(초기)


#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;

map<char, int> Map;

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(0);
    int Odd_Cnt = 0;

    string str;
    getline(cin, str);
    for (int i = 0; i < str.length(); i++) {
        Map[str[i]]++;
        //key 값으로 자동 정렬 : A - Z
    }

    for (auto element : Map) {
        if (element.second % 2 == 1) {
            Odd_Cnt++;
        }
    }

    if (Odd_Cnt > 1) {
        cout << "I'm Sorry Hansoo" << '\n';
    }
    else {

        char Odd = NULL;
        for (auto element : Map) {
            if (element.second % 2 == 1) {
                Odd = element.first;
                break;
            }
        }

        string str = "";
        for (auto element : Map) {
            int size = element.second / 2;
            for (int i = 0; i < size; i++) {
                str += element.first;
            }
        }

        string temp = str;
        reverse(str.begin(), str.end());

        if (Odd == NULL) {
            cout << temp << str << '\n';
        }
        else {
            cout << temp << Odd << str << '\n';
        }

    }

}

전체 코드(리팩토링)


#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;

string str;
int alpha[26];
int Odd_Cnt = 0;


void Fast() {
	cin.tie(0);
	ios::sync_with_stdio(0);
}

void Available() {
	for (char c : str) {
		alpha[c - 'A']++;
	}
	for (int i = 0; i < 26; i++) {
		if (alpha[i] % 2 == 1) {
			Odd_Cnt++;
		}
	}
}


int main() {

	Fast();
	getline(cin, str);
	Available();
	
	if (Odd_Cnt > 1) {
		cout << "I'm Sorry Hansoo" << '\n';
	}
	else {
		char Odd = NULL;
		for (int i = 0; i < 26; i++) {
			if (alpha[i] % 2 == 1) {
				Odd = i + 'A';
			}
		}

		for (int i = 0; i < 26; i++) {
			int half = alpha[i] / 2;
			for (int j = 0; j < half; j++) {
				cout << char(i + 'A');
			}
		}
		if (Odd != NULL) {
			cout << Odd;
		}
		for (int i = 25; i >= 0; i--) {
			int half = alpha[i] / 2;
			for (int j = 0; j < half; j++) {
				cout << char(i + 'A');
			}
		}


	}


}
profile
SSAFY 11th

0개의 댓글