티스토리 뷰
올바른 괄호의 조건
1. 시작은 (
2. 끝은 )
3. (와 )의 개수가 같다.
여기서 3번을 위해 (를 -1, (를 1로 바꾸어보았다. 조건은 다음과 같이 바뀐다.
1. 시작값은 -1
2. 끝값은 1
3. 괄호를 더한 값이 0이어야 한다.
하지만 더 고려할 게 있다.
괄호는 아직 남아있는데 3번을 충족하는 경우이다. 이 경우에 이전 괄호는 TRUE로 매듭이 지어진 상태이고, 새로운 괄호가 시작된다.
따라서 재귀함수로 구성하였다.
괄호에 따른 -1 혹은 1을 저장할 곳은 queue를 이용했다.
선입선출 + 굳이 index 없이도 Dequeue로 값이 알아서 빠져줌 + 그 값을 다시 쓰지도 않는다. (더하고 끝이지)
조건은 Count로 검사
static bool isRightBrackets(ref Queue<int> queue)
{
int checkPoint = 0;
if (queue.Peek() == 1)
return false;
while (queue.Count != 0)
{
if (queue.Count == 1)
{
if (queue.Peek() == -1)
return false;
}
checkPoint += queue.Dequeue();
if (checkPoint == 0 && queue.Count != 0)
return isRightBrackets(ref queue);
}
if (checkPoint == 0)
return true;
return false;
}
static void Main(string[] args)
{
int count = int.Parse(Console.ReadLine());
Queue<int> brackets = new Queue<int>();
string str;
for(int i = 0; i<count; i++)
{
str = Console.ReadLine();
for(int x = 0; x<str.Length;x++)
{
if (str[x].Equals('('))
brackets.Enqueue(-1);
else
brackets.Enqueue(1);
}
if (isRightBrackets(ref brackets))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
brackets.Clear();
}
}
이 문제는 재밌었다.
'■ 알고리즘 > ◻ 백준' 카테고리의 다른 글
[C#]백준 1966번 : 프린터 큐 (0) | 2018.08.10 |
---|---|
[C#] 백준 10845번 : 큐 (0) | 2018.08.09 |
[C#]백준 10828번 : 스택 (0) | 2018.08.09 |
[C#]백준 10823번 : 더하기 2 (0) | 2018.08.09 |
[C#]백준 10820번 : 문자열 분석 (0) | 2018.08.09 |