[BOJ 2504] ๊ด„ํ˜ธ์˜ ๊ฐ’

 

1. ๋ฌธ์ œ : Link

(์•ˆ) X2

[์•ˆ] X3

๊ฐ™์€ ๊ด„ํ˜ธ ์•ˆ์€ +

 

ex) ( ( ) [ [ ] ] ) 

[[]] = [] ์•ˆ์— []  = 3 X 3

() + [[]] = 2 + 9 = 11

(()+[[]]) = 11 X 2 = 22

 

2. ํ’€์ด

์Šคํƒํ’€๋•Œ ์•ž์œผ๋กœ case๋กœ ๊น”๋”ํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜๊ธฐ

ํ•ด๋‹น ๊ด„ํ˜ธ ์•ˆ์—์„œ ๊ณฑ์…ˆ์ด ์œ ์ง€๋˜๋Š” ๊ฐœ๋…์„ ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š”์ง€๊ฐ€ ์ค‘์š”

์—ฌ๊ธฐ์„œ๋Š” (,[๊ฐ€ ์ถ”๊ฐ€๋ ๋•Œ๋งˆ๋‹ค ๊ฐ’์„ ๊ณฑํ•ด์ฃผ๊ณ  -> ์œ ์ง€

๊ทธ๋Ÿฌ๋‹ค๊ฐ€ ),]๊ฐ€ ๋‚˜์™”์„๋•Œ ๋‚˜๋ˆ ์ฃผ๊ธฐ

()๊ฐ™์€ ์Œ์ด ๋‚˜์˜ฌ๋•Œ ๊ฒฐ๊ตญ ์ตœ์ข…๊ฐ’์ด ๊ฒฐ๊ณผ์— ๋”ํ•ด์ง€๋Š” ๊ฐœ๋…

 

 

3. ์ฝ”๋“œ

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String in = scanner.next();

        int mul = 1;
        int result = 0;
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < in.length(); i++) {
            switch (in.charAt(i)) {
                case '(':
                    stack.push('(');
                    mul *= 2;
                    break;
                case '[':
                    stack.push('[');
                    mul *= 3;
                    break;
                case ')':
                    if (stack.isEmpty() || stack.peek() != '(') {
                        result = 0;
                        break;
                    }
                    if (in.charAt(i - 1) == '(') result += mul;
                    stack.pop();
                    mul /= 2;
                    break;
                case ']':
                    if (stack.isEmpty() || stack.peek() != '[') {
                        result = 0;
                        break;
                    }
                    if (in.charAt(i - 1) == '[') result += mul;
                    stack.pop();
                    mul /= 3;
                    break;
            }
        }

        System.out.println(!stack.isEmpty() ? 0 : result);
    }
}

 

  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ