본문 바로가기

Algorithm/BAEKJOON

[BOJ] 9012번 괄호 (C++)

728x90
반응형

https://www.acmicpc.net/problem/9012

 

9012번: 괄호

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고

www.acmicpc.net

 

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n;
	cin >> n;

	
	for(int i = 0; i < n; i++){
		stack<char> s;
		string str;
		cin >> str;
		
		bool check = true;
		for(int j = 0; j < str.length(); j++){
			char c = str[j];
			
			if(c == '('){
				s.push(str[j]);
			} else{
				if(!s.empty()) {
					s.pop();
				} else {
					check = false;
					break;
				}
			}
		}
		
		if(!s.empty()) check = false;
		
		if(check)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}

여는 괄호일 때 

push

닫는 괄호일 때

스택 내부에 여는 괄호가 있다 -> pop

없다 -> false

문자열을 다 확인했는데

스택 내부에 여는 괄호가 있다 -> false

728x90
반응형