SHyeonL / Future_Internet_LAB_Algorithm

미래 인터넷 연구실 알고리즘 스터디
0 stars 0 forks source link

10799 (쇠막대기) #2

Closed jihwankim128 closed 1 year ago

jihwankim128 commented 1 year ago
#include <bits/stdc++.h>

using namespace std;

string str;
stack<char> st;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);

    cin >> str;

    int cnt = 0;

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

    cout << cnt;
    return 0;
}
  1. ( -> push
  2. ) -> 바로 이전이 ) 일 경우, 레이저를 만났거나 하나의 막대의 작업이 끝났다는 의미이므로 마지막으로 잘려나갈 막대의 개수만 세어준다. 그 이외에는 stack의 남은 개수만큼 세어준다.
SHyeonL commented 1 year ago
# 10799번 - 쇠막대기
import sys

input = sys.stdin.readline

s = list(input().strip())
i = 0
cnt = 0
stack = []
for i in range(len(s)):
    if s[i] == '(':
        stack.append(i)
    elif s[i] == ')':
        if i - stack[-1] == 1:
            stack.pop()
            cnt += len(stack)
        else:
            stack.pop()
            cnt += 1
print(cnt)
yuneojin commented 1 year ago
import sys
input = sys.stdin.readline

s = input().strip()
stack = []
answer = 0

for i,j in enumerate(s):
    if j == "(":
        stack.append(i)
    else:
        if i-stack[-1] == 1:
            stack.pop()
            answer += len(stack)
        else:
            stack.pop()
            answer += 1

print(answer)