https://www.acmicpc.net/problem/4949
영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어진 문자열이 입력되는데 해당 문자열의 괄호들이 모두 짝을 제대로 이루는지 판단하는 문제다.
([Hello world]hi)
yes
([Hi)hi]
no
괄호가 2개라서
1) 대괄호, 소괄호 각각 짝을 이루는지
2) 대괄호 소괄호 순서가 올바른지 체크해야한다.
예를 들어([Hi)hi]
는 괄호들이 각각 짝을 이뤘지만 대괄호 소괄호 간 등장 순서가 엉켜있어서 틀린 문장이 된다.
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string s;
int main() {
while (1) {
getline(cin, s);
if (s == ".")break;
stack<char> stk;
int flag = 1;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(' || s[i] == '[')stk.push(s[i]);
else {
if (s[i] == ')') {
if (!stk.empty() && stk.top() == '(') stk.pop();
else {
flag = 0;
break;
}
}
if (s[i] == ']') {
if (!stk.empty() && stk.top() == '[') stk.pop();
else {
flag = 0;
break;
}
}
}
}
if (flag==1&&stk.empty()) cout << "yes\n";
else cout << "no\n";
}
}