[백준] PS/Java [실랜디]

[백준 2257] 화학식량 - JAVA

SH3542 2025. 3. 17. 21:00

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

 

stack 문제

'('는 2~9에 포함되지 않는 임의의 값 0 등으로 설정한다.

 

 

1. 알파벳

map에서 해당하는 숫자를 push

 

2. 숫자

pop을 곱해서 push

 

3. (

push 0

 

4. )

top이 0이 아닌동안 pop하며 sum 누적

0을 만나면 pop하고 sum push

 

이후 stack에 남은 모든 원소를 더해서 출력한다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

class Main {

  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();

    Stack<Integer> s = new Stack<>();
    Map<Character, Integer> m = new HashMap<>();
    m.put('H', 1);
    m.put('C', 12);
    m.put('O', 16);

    for (int i = 0; i < str.length(); i++) {

      char c = str.charAt(i);

      if (Character.isAlphabetic(c)) {
        s.push(m.get(c));
      } else if (Character.isDigit(c)) {
        s.push(s.pop() * (c - '0'));
      } else if (c == '(') {
        s.push(0);
      } else {
        int cur;
        int sum = 0;
        while ((cur = s.pop()) != 0) {
          sum += cur;
        }

        s.push(sum);
      }
    }

    int ans = 0;
    for (int e : s) {
      ans += e;
    }
    System.out.println(ans);
  }
}