본문 바로가기

자료구조

스택 연습문제 (세상의 균형)

using System;
using System.Collections;

namespace HelloWorld
{
    class App
    {
        //멤버변수
        Stack stack;
        private int count;
        private bool isGood;
        string str;
        string[] arr;
        string[] arr2;

        //생성자
        public App()
        {
            judgment("So when I die (the (first) I will see in (heaven) is a score list)");
            judgment("( first in ) ( first out )");
            judgment("Half Moon tonight (At least it is better than no Moon at all");
            judgment("A rope may form )( a trail in a maze");
            judgment("Help( I(m being held prisoner) in a fortune cookie factory)");
        }

        //멤버 메서드
        void judgment(string sentence)
        {
            count = 0;
            stack = new Stack();
            isGood = false;
            str = sentence;
            arr = new string[str.Length];

            for (int i = 0; i < str.Length; i++)
            {
                string w = str[i].ToString();   //변수w에 값을 분리해서 넣고
                arr[i] = w;                 //배열arr에 w값을 넣는다.
            }

            //배열의 요소를 스택에 넣으면서 규칙수행.
            foreach (string ele in arr)
            {
                stack.Push(ele);
                if (ele != "(")
                {
                    stack.Pop();
                }
                if (ele == ")")
                {
                    if (stack.Count != 0)       //예외처리
                    {
                        stack.Pop();
                    }
                }
            }

            //현재 스택의 요소를 보기위해 또다른 배열에 넣는다.
            arr2 = new string[stack.Count];
            Console.Write("남은 스택 요소 : ");
            foreach (string ele in stack)
            {
                arr2[count++] = ele;
                Console.Write("{0}", arr2[count - 1]);
            }
            if (stack.Count == 0)
            {
                this.isGood = true;
            }
            Console.WriteLine();
            if (isGood == true)
            {
                Console.WriteLine("Good");
            }
            else
            {
                Console.WriteLine("Bad");
            }
            Console.WriteLine();
        }
    }
}