홍시홍의 프로그래밍

[백준 9012] 괄호 본문

알고리즘 문제풀이/백준

[백준 9012] 괄호

홍시홍 2020. 5. 28. 19:06

분류 

구현

요구사항

주어진 괄호가 정상인지 판단하기

풀이

기본적인 문제다

'('가 들어오면 stack에 넣어주고 ')'가 들어올 경우 top을 확인해서 '('일 경우 NO

'(' 아닐 경우, YES

계산이 끝난 후 스택이 비어있으면 YES 아니면 NO

 

#include <iostream>
#include <queue>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
int n;
int main(){
	scanf("%d",&n);
	for(int tc=1;tc<=n;tc++){
		int flag=0;
		deque<char> st;
		string str;
		cin>>str;
		for(int i=0 ; i <str.size() ; i++){
			char now = str[i];
			if(now == ')'){
				if(st.empty()){
					flag=1;
					break;
				}
				else{
					char next1 = st.back();
					if(next1 == '(')
						st.pop_back();
					else {
						flag=1;
						break;
					}
				}
			}
			if(now=='('){
				st.push_back(now);
			}
			for(int j=0 ; j <st.size() ; j++){
				//cout<<st[j]<<" ";
			}
			//cout<<endl;
		}
		if(flag==1){ 
			printf("NO\n");
			continue;
		}
		
		if(st.empty()) printf("YES\n");
		else printf("NO\n");
	}
}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 17825] 윷놀이  (0) 2020.06.05
[백준 16918] 붐버맨  (0) 2020.05.28
[백준 14923] 미로 탈출  (0) 2020.05.27
[백준 17090] 미로 탈출하기  (0) 2020.05.27
[백준 14891] 톱니바퀴  (0) 2020.05.26
Comments