본문 바로가기

c++/Baekjoon Online

백준 1254 : 팰린드롬 만들기

www.acmicpc.net/problem/1254

 

1254번: 팰린드롬 만들기

동호와 규완이는 212호에서 문자열에 대해 공부하고 있다. 규완이는 팰린드롬을 엄청나게 좋아한다. 팰린드롬이란 앞에서부터 읽으나 뒤에서부터 읽으나 같게 읽히는 문자열을 말한다. 동호는 �

www.acmicpc.net

 

1. 처음에 바보같이 맨 뒤에만 문자 추가할 수 있다는거 못보고 insert를 써서 풀었었다

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


int main()
{
	string a;
	cin >> a;
	int flag = 1;
	while (flag == 1)
	{
		flag = 0;
		int start_index = 0;
		int end_index = a.size() - 1;

		while (start_index < end_index)
		{
			if (a[start_index] == a[end_index])
			{
				start_index++;
				end_index--;
			}
			else
			{
				a.insert(a.begin() + end_index + 1, a[start_index]);
				flag = 1;
				break;
			}
		}

	}
	cout << a.size();
	return 0;
}

 

2. 후에 구글링해서 이런 알고리즘이 있는걸 깨닫고 풀었숩니다.

 눈이 번뜩 뜨이네유

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

string S;
int length;



bool palindrome(int idx)
{
	for (int i = 0; idx + i < length - i - 1; i++)
		if (S[idx + i] != S[length - i - 1])
			return false;

	return true;

}



int main(void)
{
	cin >> S;
	length = S.size();
	int result = 0;

	for (int i = 0; i < length; i++)
		if (palindrome(i))
		{
			result = length + i;
			break;
		}

	cout << result << endl;
	return 0;
}