[백준] 24552 올바른 괄호
#include <iostream>
#include <string>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
string S;
cin >> S;
int cnt = 0;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '(') cnt++;
else cnt--;
}
if (cnt < 0) {
string newS = "";
for (int i = S.length() - 1; i>= 0; --i) {
if (S[i] == '(') newS += ')';
else newS += '(';
}
S = newS;
}
int endIdx = -1;
int idx = 0;
stack<char> st;
while (idx < S.length()) {
if (st.empty()) {
st.push(S[idx]);
}
else {
if ((st.top() == '(') && (S[idx] == ')')) st.pop();
else st.push(S[idx]);
}
if (st.empty()) endIdx = idx;
idx++;
}
if(endIdx != -1) S = S.substr(endIdx + 1);
int answer = 0;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '(') answer++;
}
cout << answer;
return 0;
}