본문 바로가기
코딩테스트 준비/백준

[백준] 2257번 - 화학식량 [Java]

by mwzz6 2025. 2. 18.

https://www.acmicpc.net/problem/2257

 

[백준] 2257번 - 화학식량 [Java]
[백준] 2257번 - 화학식량 [Java]


1.  아이디어

 

Stack 자료구조를 활용하면 간단하게 해결할 수 있다.


2. 문제풀이

 

괄호와 화학식량을 모두 넣기 위해 String 객체를 받는 Stack을 만들었다. 숫자가 등장하면 이전 화학식에 곱해야하므로 Stack에서 꺼내서 곱하고 다시 넣었고, 열린 괄호나 원소면 숫자로 변경해서 넣었다. 닫힌 괄호면 열린 괄호가 나올 때까지 꺼내서 더한 후 다시 Stack에 넣으면 된다.


3. 코드

 

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Deque<String> stack = new ArrayDeque<>();

        char[] input = br.readLine().toCharArray();
        for (char c : input) {
            if (c == ')') {
                int sum = 0;
                while (true) {
                    String item = stack.pop();
                    if (item.equals("(")) {
                        stack.push(Integer.toString(sum));
                        break;
                    }

                    sum += Integer.parseInt(item);
                }
            } else if ('1' <= c && c <= '9') {
                stack.push(Integer.toString(Integer.parseInt(stack.pop()) * Character.getNumericValue(c)));
            } else {
                if (c == 'H') {
                    stack.push(Integer.toString(1));
                } else if (c == 'C') {
                    stack.push(Integer.toString(12));
                } else if (c == 'O') {
                    stack.push(Integer.toString(16));
                } else {
                    stack.push(Character.toString(c));
                }
            }
        }

        int sum = 0;
        while (!stack.isEmpty()) {
            sum += Integer.parseInt(stack.pop());
        }

        System.out.println(sum);
    }
}

4. 후기