๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 2257_ํ™”ํ•™์‹๋Ÿ‰

๋ฟŒ์•ผ._. 2023. 8. 28. 19:41

Silver II

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/2257)

< ํ™”ํ•™์‹๋Ÿ‰ >

 

๋ฌธ์ œ ํ’€์ด 

 

Stack์„ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ์—์„œ ๋งํ•œ ๋ช…๋ น๋Œ€๋กœ ๊ตฌํ˜„ํ•œ๋‹ค.

 

 

 my solution (Java)

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

public class _2257_ { // ํ™”ํ•™์‹๋Ÿ‰

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

		String str = bf.readLine();

		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < str.length(); i++) {
			Character ch = str.charAt(i);
			if (ch == 'C') {
				stack.add(12);
			} else if (ch == 'O') {
				stack.add(16);
			} else if (ch == 'H') {
				stack.add(1);
			} else if (Character.isDigit(ch)) {
				int num = stack.pop();
				stack.add(num * (ch - '0'));
			} else if (ch == '(') {
				stack.add(-1);
			} else if (ch == ')') {
				int num = 0;
				while (stack.peek() != -1) {
					num += stack.pop();
				}
				stack.pop();
				stack.add(num);
			}
		}

		int result = 0;
		while (!stack.isEmpty()) {
			result += stack.pop();
		}

		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
str : ํ™”ํ•™์‹
stack : Stack <Integer> 
result : ํ™”ํ•™์‹๋Ÿ‰

 

- ํ™”ํ•™์‹(str) ์ž…๋ ฅ

- ํ™”ํ•™์‹(str) ํƒ์ƒ‰

: ํƒ„์†Œ(C)๋ผ๋ฉด stack์— 12 ์ถ”๊ฐ€

: ์‚ฐ์†Œ(O)๋ผ๋ฉด stack์— 16 ์ถ”๊ฐ€

: ์ˆ˜์†Œ(H)๋ผ๋ฉด stack์— 1 ์ถ”๊ฐ€

: ์ˆซ์ž๋ผ๋ฉด ์•ž์— ๊ฐ’๊ณผ ๊ณฑํ•ด์•ผ ํ•˜๋ฏ€๋กœ stack์—์„œ popํ•ด์˜จ ๊ฐ’์„ ๊ณฑํ•ด์„œ stack์— ์ถ”๊ฐ€

: '(' ๋ผ๋ฉด '('๋ฅผ ํ‘œ์‹œํ•˜๊ธฐ ์œ„ํ•ด stack์— -1 ์ถ”๊ฐ€

: ')' ๋ผ๋ฉด ๊ด„ํ˜ธ ์•ˆ์— ๊ฐ’์„ ๋‹ค ๋”ํ•ด์•ผ ํ•˜๋ฏ€๋กœ '('์„ ๋œปํ•˜๋Š” -1์ด ๋‚˜์˜ฌ ๋•Œ๊นŒ์ง€ stack์—์„œ ๊ฐ’์„ pop ํ•ด์„œ ๋”ํ•œ ํ›„ stack์— ์ €์žฅ

- stack์— ๋ชจ๋“  ๊ฐ’์„ ๊บผ๋‚ด์„œ ๋”ํ•œ ๊ฐ’์„ ์ถœ๋ ฅ