C#/수업 내용

[C#] 2021-09-02 Stack 연습문제

JSH1 2021. 9. 2. 16:56

문자열 뒤집기

            Stack stack = new Stack();
            string str = "안녕하세요";

            foreach(char c in str)
            {
                Console.WriteLine(c);

                stack.Push(c);
            }
            Console.WriteLine();

            for (int i=0; i<str.Length; i++)
            {
                Console.WriteLine(stack.Pop());
            }


            Stack stack = new Stack();
            int count = 0;
            string input = Console.ReadLine();

            foreach(char c in input)
            {
                stack.Push(c);

                if (stack.Pop().ToString() != "0")
                {
                    count++;
                }
            }

            Console.WriteLine(count);


            Stack stack = new Stack();

            string[] text =
              { "So when I die (the (first) I will see in (heaven) is a score list)",
                "( first in ) ( first out )",
                "Half Moon tonight (At least it is better than no Moon at all",
                "A rope may form )( a trail in a maze",
                "Help( I(m being held prisoner) in a fortune cookie factory)" };

            for (int i = 0; i < text.Length; i++)
            {
                foreach (char c in text[i])
                {
                    stack.Push(c);
                }

                int stackCount = stack.Count;
                int openCount = 0;
                bool open = false;
                for (int j = 0; j < stackCount; j++)
                {
                    string check = stack.Pop().ToString();

                    if (open == false)
                    {
                        if (check == ")")
                        {
                            open = true;
                            openCount++;
                        }

                        else if (check == "(")
                        {
                            Console.WriteLine("균형이 맞지 않습니다.");
                            return;
                        }
                    }

                    else
                    {
                        if (check == ")")
                        {
                            openCount++;
                        }

                        else if (check == "(")
                        {
                            openCount--;
                        }
                    }
                }

                if (openCount != 0)
                {
                    Console.WriteLine("균형이 맞지 않습니다.");
                    return;
                }

                else
                {
                    open = false;
                    openCount = 0;
                }
            }
            Console.WriteLine("균형이 맞습니다.");

 

첫줄 끝에 ), 둘째 줄 처음에(, 끝에 ) 추가

                "Half Moon tonight (At least it is better than no Moon at all)",
                "(A rope may form )( a trail in a maze)",