본문 바로가기
  • Let's study
PS/백준

[C++] 백준 10799번: 쇠막대기

by 코딩고수이고파 2021. 2. 4.

')'가 입력될 때 이전 괄호가 '('이면 현재까지 저장된 '(' 개수를 더해주고 이전 괄호가 ')'라면 1을 더해준다.


#include<iostream>
#include<string>
#include<stack>

using namespace std;

stack<char> s;

int main() {
	string str;
	cin >> str;

	int res = 0;
	for (int i = 0; i < str.size(); i++) {
		if (str[i] == '(') {
			s.push(str[i]);
		}
		else {
			s.pop();
			if (str[i - 1] == '(') {
				res += s.size();
			}
			else {
				res ++;
			}
		}
	}
	cout << res;
}

댓글