PS/문자열 알고리즘[String]

백준 1213 팰린드롬 만들기(c++)

SeungbeomKim 2022. 7. 27. 20:19
반응형

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

 

1213번: 팰린드롬 만들기

첫째 줄에 문제의 정답을 출력한다. 만약 불가능할 때는 "I'm Sorry Hansoo"를 출력한다. 정답이 여러 개일 경우에는 사전순으로 앞서는 것을 출력한다.

www.acmicpc.net

<코드>

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
	string str;
	int alpha[26]={0};
	
	cin>>str;
	
	for(int i=0;i<str.size();i++)
	{
		alpha[str[i]-'A']++;
	}
	int cnt=0;
	string frontans="";
	string centerans="";
	string backans="";
	for(int i=0;i<26;i++)
	{
		if(alpha[i]%2==1){
			cnt++;
			centerans+=i+'A';
		}
		for(int j=0;j<alpha[i]/2;j++)
		{
			frontans+=i+'A';
		}
		for(int k=0;k<alpha[25-i]/2;k++)
		{
			backans+=25-i+'A';
		}
	}
	if(cnt>1) {
		cout<<"I'm Sorry Hansoo";
		return 0;
	}
	else
	{
	if(frontans!="")
	{
		cout<<frontans;
	}
	if(centerans!="")
	{
		cout<<centerans;
	}
	if(backans!="")
	{
		cout<<backans;
	}
	}
}

<풀이과정>

우선적으로 알파벳의 가중치를 할당시켜준다.(alpha[str[i]-'A']++) 예시를 들어 AABBCC라고 가정하면 순차적으로 alpha[0],alpha[1],alpha[2]의 개수를 2개 늘려줘야 한다. ('A'-'A'=0,'B'-'A'=1,'C'-'A'=2)가 되기 때문이다.  

그리고 팰린드롬은 알파벳의 개수가 홀수인 경우가 2개이상이 되면 팰린드롬을 만들 수 없다. 예시를 들어 AAABBB는 좌우가 대칭인 팰린드롬을 만들 수 없다.

그리고 순서대로 앞부분(알파벳의 개수가 짝수개인데 오름차순 정렬된 알파벳), 중간부분(알파벳의 개수가 홀수), 뒷부분(알파벳의 개수가 짝수개인데 내림차순 정렬된 알파벳)을 더해주고 출력해주면 끝이다. 

반응형