백준 1213 팬린드롬 만들기 ❗

CJB_ny·2023년 1월 1일
0

백준

목록 보기
32/104
post-thumbnail
#include <iostream>
#include <string>
#include <map>
using namespace std;
#define endl "\n";

string s;
map<char, int> ma;
char arr[26];
int arr2[26];

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> s;

	for (int i = 0; i < s.size(); ++i)
	{
		++ma[s[i]];
		arr[s[i] - 'A'] = s[i];
	}

	int re = 0;
	int idx = 0;
	for (auto va : ma)
	{
		if (va.second % 2 == 1)
		{
			++re;
			idx = va.first - 'A';
			arr2[va.first - 'A'] = va.second;
		}		
	}

	if (re >= 2)
	{
		cout << "I'm Sorry Hansoo";
		return  0;
	}
	else if (re == 1)
	{
		for (int i = 0; i < arr2[idx]; ++i)
		{
			

			
		}
	}
	else if (re == 0)
	{
		int a = 10;

	}
	return 0;
}

처음에 위와같이 매우 더럽고 길게 만들었다. 알파벳이 몇개인지 새는 부분

for(char c : s ) cnt[i]++; 
// 이렇게 안해버림..

풀이 및 분석 👍👍👍

#include <iostream>
#include <string>
#include <map>
using namespace std;
#define endl "\n";

string s, ret;
int cnt[200], flag;
char mid;

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> s;

	for (char a : s) cnt[a]++;
	for (int i = 'Z'; i >= 'A'; --i)
	{
		if (cnt[i] & 1)
		{
			mid = char(i); ++flag;
			--cnt[i];
		}

		if (flag == 2) break;
		for (int j = 0; j < cnt[i]; j += 2)
		{
			ret = char(i) + ret;
			ret += char(i);
		}
	}

	if (mid) ret.insert(ret.begin() + ret.size() / 2, mid);
	if (flag == 2) cout << "I'm Sorry Hansoo";
	else cout << ret << endl;
	
	return 0;
}

앞뒤로 붙이기

일단 오름차순으로 알파벳이 (아스키 기준) 큰것부터 다 때려박아 넣는데

"앞 뒤로" 넣는 부분이

for (int j = 0; j < cnt[i]; j += 2)
{
	ret = char(i) + ret;
	ret += char(i);
}

위의 코드처럼 된다.

이거 처음에 무슨 코드인지 이해가 안갔는데

ret = 'A' + 'AB' 이렇게 하면

ret는 'AAB'이렇게 된다음에 ret += 'A'해버리면

ret 'B'다음에 'A'가 붙는 식으로 되는 부분이다.

카운팅 배열

매번 하면서도 계속 까먹기도하고

문제에 맞게 카운팅 배열을 만드는 부분이 아직 많이 어렵다.

또한

for (int i = 0; i < s.size(); ++i)
	cnt[i]++;
    
이거나

for (char c : s)
	cnt[c]++;
    
이거랑 똑같은데 이거 사용을 또 안함...

삽입

mid를 기억해둔 다음에 나중에 insert로 삽입하는 부분

f (mid) ret.insert(ret.begin() + ret.size() / 2, mid);

https://modoocode.com/186

profile
https://cjbworld.tistory.com/ <- 이사중

0개의 댓글