#include <iostream> #include <stack> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int number = 1; while(1) { stack<char> s; string str; cin >> str; int cnt=0; if(str[0] == '-') break; for(int i=0;i<str.length();i++) { char a = str[i]; if(a == '}') { if(s.empty()) { s.push('{'); cnt++; }else{ s.pop(); } }else if(a == '{') { s.push(a); } } if(!s.empty()) cnt += s.size()/2; cout << number++ << ". "<< cnt <<'\n'; } }
- '}' 일 때 stack이 비어있으면 cnt++ 후 '{'로 stack에 삽입!
- '{{{{{{' 처럼 '{'이 연속으로 있을 경우 하나만 '{'개수의 절반만 바뀌면 올바른 괄호가 된다. --> cnt += s.size()/2;
- 입력에서 '-'가 1개 이상 있다고해서 str.find()로 찾아서 했는데 이게 오류의 원인이었음; 어휴 그냥 str[0] != '-' 하면될것을;