[C++]SWEA 1218번 괄호 짝짓기

1 minute read

오늘은 SWEA 1218번 괄호 짝짓기 문제를 풀어보도록 하자.

스택을 4개 써서 풀 수 있지만 하나만 써서 top과 비교해주는 방식으로 하면 메모리 관리에서 효율적인 코드를 짤 수 있다.

중복코드가 좀 있어서 아쉽다. 나중에 중복코드를 처리해봐야겠다.

문제는 다음과 같다.

                               [접근법]

  1. ( 가 top일 때 )가 나오면 pop, 만일 [ 가 top인데 }가 나오면 answer = 0 으로 하고 break
                                     [코드]
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);

	string txt;
	int T = 10, i = 0, num;
	stack<char>txt_stack;


	while (T--) {
		int answer = 1;
		cin >> num;
		cin >> txt;
		for (int i = 0; i < txt.length(); i++) {
			if (txt[i] == '(' || txt[i] == '{' 
				|| txt[i] == '[' || txt[i] == '<') {
				txt_stack.push(txt[i]);
			}
			else {
				if (!txt_stack.empty()) {
					if (txt[i] == ')') {
						if (txt_stack.top() != '(') {
							answer = 0;
							break;
						}
						txt_stack.pop();
					}
					else if (txt[i] == '}') {
						if (txt_stack.top() != '{') {
							answer = 0;
							break;
						}
						txt_stack.pop();
					}
					else if (txt[i] == ']') {
						if (txt_stack.top() != '[') {
							answer = 0;
							break;
						}
						txt_stack.pop();
					}
					else if (txt[i] == '>') {
						if (txt_stack.top() != '<') {
							answer = 0;
							break;
						}
						txt_stack.pop();
					}
				}
				else {
					answer = 0;
					break;
				}
			}
		}
		if (!txt_stack.empty()) {
			answer = 0;
		}
		while (!txt_stack.empty()) {
			txt_stack.pop();
		}
		cout << '#' << ++i << ' ' << answer << '\n';
	}
}