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

SmileJun·2025년 2월 26일

알고리즘

목록 보기
2/34

문제 : https://www.acmicpc.net/problem/10799

C++

#include<iostream>
#include<stack>
using namespace std;

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

    stack<int> s;
    string str;
    int count = 0;
    cin >> str;

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

Java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        Stack<Character> s = new Stack<>();
        String str = br.readLine();
        int count = 0;

        // charAt(i) 함수는 String 타입의 데이터에서 특정 문자를 char 타입으로 변환
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == '(' && str.charAt(i+1) == ')') {
                count += s.size();
                i += 1;
            }
            else if(str.charAt(i) == '(') {
                s.push(str.charAt(i));
            }
            else if(str.charAt(i) == ')') {
                count += 1;
                s.pop();
            }
        }
        bw.write(count + "\n");
        bw.flush();
        br.close();
    }
}

문제풀이

  • ( ) 일 경우에는 레이저를 쏘고, ( )일 경우에는 막대기를 생성한다. 생성된 막대기는 레이저를 만나면 잘라진다. 먼저 '(' 경우에는, stack에 값을 push한다. 그리고 ')' 경우에는, 가장 최근의 '('와 만나서 생성된 막대기가 잘리기 때문에 총 잘린 막대기 수를 +1 해주고, stack 안에 있는 '(' pop해준다. 마지막으로 '( )' 경우에는 그 전에 stack에 담겨있는 '(' 개수만큼 더해준다.

Comment

profile
하루하루는 성실하게, 인생 전체는 되는대로

0개의 댓글