

괄호 검사 문제인데 종류가 2개이다.
괄호가 아니라면 무시하고, 괄호인 경우에 대해서만 처리해주면된다.
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
while(1) {
stack<int> st;
getline(cin,s);
bool stop = 0;
if(s==".") break;
for(char c:s) {
if(c=='(' || c=='[') st.push(c);
if(c==')') {
if(!st.empty() && st.top()=='(') st.pop();
else {
stop = 1; break;
}
} else if(c == ']') {
if(!st.empty() && st.top()=='[') st.pop();
else {
stop = 1; break;
}
}
}
(st.empty() && !stop) ? cout << "yes\n" : cout << "no\n";
}
return 0;
}
조건문을 치밀하게 설계하지않아서 빈틈이 생겼고, 거기서 오류가 발생했다.
그냥 단순하게
if(c=='(' || c=='[') st.push(c);
if(c==')') {
if(!st.empty() && st.top()=='(') st.pop();
else {
stop = 1; break;
}
} else if(c == ']') {
if(!st.empty() && st.top()=='[') st.pop();
else {
stop = 1; break;
}
}
위와 같이 모든 경우의 수에 대해 (마치 switch문 처럼) 조건문을 작성하는 방식이 실수할 확률을 감소시킬 수 있다.