Algorithm/BOJ
C# 문자열) [BOJ] 괄호 9012
HSH12345
2023. 1. 11. 17:15
https://www.acmicpc.net/problem/9012
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _230113_2
{
class Program
{
static void Main(string[] args)
{
string[] arr = {
"(())())",
"(((()())()",
"(()())((()))",
"((()()(()))(((())))()",
"()()()()(()()())()",
"(()((())()(",
};
//여기서부터 코드 작성
for (int i = 0; i < arr.Length; i++) //arr의 배열을 순회하여 배열 내부검사
{
if(arr[i][arr[i].Length - 1] == '(')
{
Console.WriteLine("NO");
}
else if (arr[i][0] == '(')
{
int leftCount = 0; //카운트 할 변수 초기화
int rightCount = 0;
for (int j = 0; j < arr[i].Length; j++) //각각 인덱스의 내부 문자열 갯수만큼 순회하여 검사
{
if (arr[i][j] == '(')
{
Stack<char> test0 = new Stack<char>(); //테스트 스택 초기화 => 각각 배열의 인덱스 내부를 확인
test0.Push(arr[i][j]);
for (int k = 0; k < test0.Count; k++) //스트링 배열의 인덱스 갯수만큼 순회하며 카운트
{
test0.Pop();
leftCount++;
}
}
else if (arr[i][j] == ')')
{
Stack<char> test1 = new Stack<char>();
test1.Push(arr[i][j]);
for (int k = 0; k < test1.Count; k++)
{
test1.Pop();
rightCount++;
}
}
}
if (leftCount == rightCount)
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
else
{
Console.WriteLine("NO");
}
}
}
}
}
더 간단하게 수정...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace _02_Bracket
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
StringBuilder ans = new StringBuilder();
int T = int.Parse(sr.ReadLine());
for(int i = 0; i < T; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(sr.ReadLine());
int cnt = 0;
for(int j = 0; j < sb.Length; j++)
{
if (sb[j] == '(') cnt++;
else cnt--;
if (cnt == -1) break;
}
if (cnt == 0) ans.AppendLine("YES");
else ans.AppendLine("NO");
}
sw.WriteLine(ans);
sr.Close();
sw.Close();
}
}
}