Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21.03.16 - [BOJ] 2504. 괄호의 값 #36

Closed
suhyunsim opened this issue Mar 15, 2021 · 0 comments
Closed

21.03.16 - [BOJ] 2504. 괄호의 값 #36

suhyunsim opened this issue Mar 15, 2021 · 0 comments
Assignees
Labels
성공 맞은 문제 스택 stack 실버 BOJ - 실버 재귀

Comments

@suhyunsim
Copy link
Owner

suhyunsim commented Mar 15, 2021

문제

핵심 아이디어

File (4)

  • 우선 계산되는 괄호들을 분리해서 생각하는 것처럼 result에 값이 쌓임

어려운 점, 실수

  • 열린 괄호가 나올 때 곱해주고 그 괄호가 닫힐 때마다 다시 나눠주는 방식을 활용하는 풀이

풀이

package main.java.com.poogle.BOJ.Q2504;

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Stack<Character> stack = new Stack<>();
        int cnt = 1;
        int result = 0;
        String line = br.readLine();
        if (line.length() % 2 == 1) { //괄호 짝 안 맞으면 0 출력
            System.out.println(0);
            return;
        }
        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == '(') {
                stack.push(line.charAt(i));
                cnt *= 2;
            } else if (line.charAt(i) == '[') {
                stack.push(line.charAt(i));
                cnt *= 3;
            } else if (line.charAt(i) == ')') {
                if (stack.isEmpty() || !stack.peek().equals('(')) {
                    System.out.println(0);
                    return;
                }
                if (line.charAt(i - 1) == '(')
                    result += cnt;
                stack.pop();
                cnt /= 2;
            } else if (line.charAt(i) == ']') {
                if (stack.isEmpty() || !stack.peek().equals('[')) {
                    System.out.println(0);
                    return;
                }
                if (line.charAt(i - 1) == '[')
                    result += cnt;
                stack.pop();
                cnt /= 3;
            }
        }
        System.out.println(result);
        br.close();
    }
}
@suhyunsim suhyunsim added 실버 BOJ - 실버 스택 stack labels Mar 15, 2021
@suhyunsim suhyunsim added this to the 3월 3주 차 milestone Mar 15, 2021
@suhyunsim suhyunsim self-assigned this Mar 15, 2021
@suhyunsim suhyunsim added the 실패 시도했지만 맞지 못한 문제 label Mar 21, 2021
@suhyunsim suhyunsim added 성공 맞은 문제 and removed 실패 시도했지만 맞지 못한 문제 labels Sep 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
성공 맞은 문제 스택 stack 실버 BOJ - 실버 재귀
Projects
None yet
Development

No branches or pull requests

1 participant