Algorithm/BOJ
C#) [BOJ] 1254 팰린드롬 만들기 ★
HSH12345
2023. 2. 14. 23:43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace _230120_1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
StringBuilder sb = new StringBuilder();
sb.Append(sr.ReadLine());
bool isSame = false;
int answer = 0;
for (int i = 0; i < sb.Length; i++)
{
int cnt = 0;
for (int j = i; j <= (sb.Length - 1) / 2; j++)
{
if (sb[j] == sb[sb.Length- 1 - cnt])
{
isSame = true;
cnt++;
}
else
{
isSame = false;
break;
}
}
if (isSame)
{
answer = sb.Length + i;
break;
}
if(i == sb.Length - 1 && !isSame)
{
answer = sb.Length * 2 - 1;
break;
}
}
sw.WriteLine(answer);
sr.Close();
sw.Flush();
sw.Close();
return;
}
}
}
예제의 출력 값은 맞는데 채점 결과는 오답.. 아마도 문자열 중 마지막 예제의 qwerty 같이 마지막까지 검사해야 팰린드롬이 되는 문자를 예외처리하였는데 이부분이 문제인 것 같다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace _230213_1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
StringBuilder sb = new StringBuilder();
sb.Append(sr.ReadLine());
int cnt = -1;
while (true)
{
bool isPelin = true;
int right = sb.Length - 1;
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == sb[right])
{
right--;
}
else
{
isPelin = false;
cnt++;
}
if (!isPelin)
{
sb.Remove(sb.Length - cnt, cnt);
for (int j = cnt; j >= 0; j--)
{
sb.Append(sb[j]);
}
break;
}
}
if (isPelin) break;
}
sw.WriteLine(sb.Length);
sr.Close();
sw.Close();
}
}
}
반례가 생길 때마다 로직을 바꿔가며 수학적 풀이 방법을 찾으려 했는데, 수학적으로 방법을 찾아서 해결하려고 시도하면 반례가 생기기 쉬운 문제였다. StringBuilder의 Append와 Remove 메서드를 사용하여 실제로 문자를 추가하고 제거하는 방법으로 문제를 풀 수 있었다.