백준 1213번

상인·2023년 2월 3일
0

문제-https://www.acmicpc.net/problem/1213
내 풀이

#include <bits/stdc++.h>
using namespace std;
int n[26];
string s,str,str1,one;
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	cin>>s;
	for(int i=0;i<s.size();i++){
		n[s[i]-'A']++;		//s string에들어간 알파뱃의 개수 배열로 카운팅
	}
	for(int i=0;i<26;i++){
		if(n[i]%2==1){ //한개의 알파뱃이 홀수개인 경우
			for(int j=0;j<n[i]/2;j++)str+=(char)('A'+i);//str배열에 1/2만큼 알파뱃 저장
			if(n[i]==1)one+=(char)('A'+i);//알파뱃이 한개인 경우 one배열에 하나 저장
			else one+=(char)('A'+i);//홀수개인 경우이기 때문에 1이아닌 홀수경우 one에 하나 저장 중앙에 드갈꺼
		}
		else for(int j=0;j<n[i]/2;j++)str+=(char)('A'+i);//짝수인 경우 1/2만큼 알파뱃저장 str배열에
	}
	if(one.size()>1){ //홀수인 알파뱃의 갯수 확인 
		cout<<"I'm Sorry Hansoo";
		return 0;
	}
	str1=str;
	reverse(str1.begin(),str1.end()); // 팰린드롬을 만들기 위해 반쪽 str을 뒤집어서str1에 저장 
	str=str+one+str1;// 반쪽 str + 홀수 알파뱃 하나 + 반쪽 뒤집은 str1 ex) AAC+B+CAA
	cout<<str;
}

또 다른 풀이

#include<bits/stdc++.h> 
using namespace std; 
string s, ret; 
int cnt[200], flag; 
char mid;
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> s;
	for(char a : s)cnt[a]++; //알파뱃별로 카운팅
	for(int i = 'Z'; i >= 'A'; i--){//중간에서 앞뒤로 붙히기 때문에 내림차순으로 진행 ex) B -> ABA
		if(cnt[i]){
			if(cnt[i] & 1){//홀수인경우
				mid = char(i);flag++;//flag는 홀수인 알파뱃 개수 확인 2개면 쏘리한수
				cnt[i]--;//홀수이기 때문에 3개면 2개를 붙이고 mid에 하나 저장해야하기 때문에 mid에 하나 저장
			}//그리고 반복문에서 사용을위해 1하나 감소
			if(flag == 2)break;
			for(int j = 0; j < cnt[i]; j += 2){//앞뒤로 하나씩붙이기 때문에 2씩증가
				ret = char(i) + ret; //뒤에 하나
				ret += char(i);//앞에 하나
			}
		}
	}
	if(mid)ret.insert(ret.begin() + ret.size() / 2, mid);//문자열 중간에 mid를 삽입
	if(flag == 2)cout << "I'm Sorry Hansoo\n";
	else cout << ret << "\n"; 
}
profile
상상그이상인

0개의 댓글