[9012] 괄호

RudinP·2023년 4월 25일
0

BaekJoon

목록 보기
60/77

생각

이정도는 대학생이었다면 한번쯤은 과제로 겪어봤을 만한 문제다.
(은 push 하고 )가 들어오면 TryPop 해보고 안되면 NO인거다.
마지막에 스택이 비어있지 않으면 NO를, 비어있다면 YES를 출력해주면 된다.

처음 코드

namespace SongE
{
    public class Program
    {
        static void Main(string[] args)
        {
            StreamReader input = new System.IO.StreamReader(Console.OpenStandardInput());

            int intInput() => int.Parse(input.ReadLine());
            //int[] intsInput() => Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            int n = intInput();

            for(int i = 0; i < n; i++)
            {
                IsVPS(input.ReadLine());
            }
        }

        static void IsVPS(string s)
        {

            bool isVPS = true;

            Stack<char> stack = new Stack<char>();

            foreach (char c in s)
            {
                if(c == '(')
                    stack.Push(c);
                else if(c == ')')
                {
                    if(!stack.TryPop(out char a))
                    {
                        isVPS = false;
                        break;       
                    }
                }
            }
            if(stack.Count > 0) isVPS = false;

            Console.WriteLine(isVPS ? "YES" : "NO");
        }
        
    }
}

profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글