Rylah's Study & Daily Life

04. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기 (1218) 본문

SW Expert Academy/Programming Intermediate

04. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기 (1218)

Rylah 2021. 11. 19. 03:39

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14eWb6AAkCFAYD 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(int argc, char** argv) {
	//freopen("input.txt", "r", stdin);
	int testCase = 10;
	
	string s;
	bool isTrue;
	for (int t = 1; t <= testCase; t++) {
		int length;
		cin >> length;
		cin >> s;
		stack<char> st;
		isTrue = true;
		
		for (int i = 0; i < length; i++) {
			if ( (s[i] == '(') || (s[i] == '[')
			 ||  (s[i] == '{') || (s[i] == '<') ) { // 열린 괄호가 맞다면 push 
			 	st.push(s[i]); 
			 	continue;
			 }
			 
			 if (st.empty() == true) {
			 	isTrue = false;
			 	break;
			 }
			 
			 //괄호쌍이 다르다면 false로 값 변경
			 // 이유는 반복문을 탈출하기 위해 
			 if (s[i] == ')' && st.top() != '(')	isTrue = false;
			 else if (s[i] == ']' && st.top() != '[')	isTrue = false;
			 else if (s[i] == '}' && st.top() != '{')	isTrue = false;
			 else if (s[i] == '>' && st.top() != '<')	isTrue = false;
			 
			 // 만약에 이 문구르 지나서 틀렸다면
			 if (isTrue == false) break;
			 
			 // 괄호쌍이 맞다면 pop 해준다. 
			 st.pop(); 
			 
		}
		
		if (st.size() > 0) isTrue = false; // 모든 반복문이 종료되었는데 스택이 비지 않았다면 false
		
		cout << "#" << t << " ";
		if (isTrue == true) cout << "1" << endl;
		else cout << "0" << endl;
	}
	return 0;
}