모든 괄호는 짝을 이루어야 한다 () / []
괄호는 서로 다른 괄호끼리 짝을 이룰 수 없다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
namespace 연습장
{
internal class Program
{
//static List<int> stack = new List<int>();
static StringBuilder sb = new StringBuilder();
static void Main(string[] args)
{
using var reader = new StreamReader(Console.OpenStandardInput());
using var print = new StreamWriter(Console.OpenStandardOutput());
while (true)
{
string str = Console.ReadLine();
Stack<char> stack = new Stack<char>();
if (str == ".")
break;
bool yes = true;
foreach (char s in str)
{
switch (s)
{
case '(':
case '[':
{
stack.Push(s);
break;
}
case ')':
{
if (stack.Count() == 0 || stack.Pop() != '(')
yes = false;
break;
}
case ']':
{
if (stack.Count() == 0 || stack.Pop() != '[')
yes = false;
break;
}
}
if (!yes)
break;
}
if (stack.Count == 0 && yes)
sb.Append("yes\n");
else
sb.Append("no\n");
}
print.WriteLine(sb);
}
}
}
|
cs |
입력을 한칸씩 돌며 조회해서 여는 괄호 '(', '[' 라면 스택에 추가하고 닫는 괄호 ')' ']' 라면 스택에서 제거한다.
하지만, 스택에서 제거한 요소가 짝이 맞지 않는다면, 짝이 맞지 않음을 bool 타입 변수를 통해 표시하고, 반복문을 종료한다.
스택의 모든 요소가 짝이 맞으면서, 제거되었다면 yes를 출력하고, 아니라면 no를 출력해주었다.