[1874] 스택 수열

RudinP·2023년 5월 2일
0

BaekJoon

목록 보기
62/77

생각


별도로 현재 수를 저장해 줄 int cur 선언.
1) cur++, 입력한 수까지 push 한다. ( + stringbuilder에 추가 )
2) 입력한 수가 되면 pop 한다. ( - stringbuilder에 추가 )
3) Peek한 값이 입력한 숫자가 아닐 경우 수열을 만드는 것이 불가능하다. ( NO 리턴 )
4) 반복

처음 코드

using System.Text;

namespace SongE
{
    public class Program
    {
        static void Main(string[] args)
        {
            int intInput() => int.Parse(Console.ReadLine());

            int n = intInput();

            string ans = StackSeq(n);

            Console.WriteLine(ans);
        }

        static string StackSeq(int n)
        {
            Stack<int> stack = new();
            StringBuilder sb = new();

            int cur = 1;

            for(int i = 0; i < n; i++) 
            {
                int num = int.Parse(Console.ReadLine());

                while(cur <= num)
                {
                    stack.Push(cur++);
                    sb.AppendLine("+");
                }

                if (stack.Peek() == num)
                {
                    stack.Pop();
                    sb.AppendLine("-");
                }
                else
                    return "NO";
            }

            return sb.ToString(); 
        }     
    }
}

profile
iOS 개발자가 되기 위한 스터디룸...

0개의 댓글