여는 괄호 (
: 스택에 push → 현재 열려 있는 막대 수를 의미.
닫는 괄호 )
:
(
이면 ()
→ 레이저: 방금 연 (
를 pop 하고, 현재 열려 있는 막대 수만큼 조각이 늘어남 → ans += st.size()
.ans += 1
.#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int ans = 0;
stack<char> st;
string str = "";
getline(cin, str);
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(') {
st.push('(');
}
else {
if (!st.empty() && str[i - 1] == '(') {
st.pop();
ans += st.size();
}
else if (!st.empty()) {
st.pop();
ans++;
}
}
}
cout << ans;
return 0;
}
)
로 시작하지 않으므로 str[i-1]
접근도 안전.