문제
알파벳 소문자로만 이루어진 단어가 주어진다. 이때, 이 단어가 팰린드롬인지 아닌지 확인하는 프로그램을 작성하시오.
팰린드롬이란 앞으로 읽을 때와 거꾸로 읽을 때 똑같은 단어를 말한다.
level, noon은 팰린드롬이고, baekjoon, online, judge는 팰린드롬이 아니다.
입력
첫째 줄에 단어가 주어진다. 단어의 길이는 1보다 크거나 같고, 100보다 작거나 같으며, 알파벳 소문자로만 이루어져 있다.
출력
첫째 줄에 팰린드롬이면 1, 아니면 0을 출력한다.
시도 1
static void Main(string[] args)
{
string word = Console.ReadLine();
char[] chars = word.ToCharArray();
List<char> list = new List<char>();
foreach (char c in chars)
{
list.Add(c);
}
list.Reverse();
for (int i = 0; i < list.Count; i++)
{
if (list[i] == chars[i])
{
Console.WriteLine("1");
break;
}
else
{
Console.WriteLine("0");
break;
}
}
}
하지만 해당 코드는 실패라고 떴다. 테스팅을 계속 거쳤는데 실패가 뜨는 정확한 이유를 알 수 없었다. 다만 처음에 string을 char 화 시켜서 담은 이유는 직접 옮길까 하다가 reverse를 사용하자 해서 좀 섞인 경향이 있는데 보면 그냥 string으로 반복문없이 가능하지 않나 싶어 두번째 시도를 해보았다.
시도 2
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodeKata60
{
internal class Program
{
static void Main(string[] args)
{
string word = Console.ReadLine();
string result = new string(word.Reverse().ToArray());
if(result == word)
{
Console.WriteLine("1");
}else
{
Console.WriteLine("0");
}
}
}
}
string으로 바로 바꾸면되는걸 굳이 복잡하게 해결한 것 같다. 그리고 아마 위 문제는 break때문에 어떠한 문제가 일어나지 않았나 싶다.
시도3 번외 Queue를 이용한 풀이
Queue에 넣고 단어 뒤에서 부터 반복을 돌려 풀이하는 방법도 가능하다.
static void Main(string[] args)
{
string word = Console.ReadLine();
Queue<char> queue = new Queue<char>();
foreach (char c in word)
{
queue.Enqueue(c);
}
bool isTrue = true;
for (int i = word.Length - 1; i >= 0; i--)
{
char c = queue.Dequeue();
if (c != word[i])
{
isTrue = false;
break;
}
}
if (isTrue)
{
Console.WriteLine("1");
}
else
{
Console.WriteLine("0");
}
}
}
먼저 입력한 단어를 queue에 넣고 하나씩 Dequeue하면서 반복문 조건을 입력한 글자의 맨 뒤부터(i값이 글자의 크기에서 줄어드는 형식) 체크하여 true인지 false인지 체크하여 검사하는 방식이다.
'백준 등 알고리즘' 카테고리의 다른 글
[C#] 백준 9012 괄호 (0) | 2024.05.08 |
---|---|
[C#] 백준 10828 스택 (0) | 2024.05.07 |
[프로그래머스] C# 소수만들기 (0) | 2024.01.10 |
[프로그래머스] 모의고사 (1) | 2024.01.08 |
[프로그래머스] 푸드파이트 (2) | 2023.12.20 |