본문 바로가기

Algorithm

[Algorithm/Java][백준] 2504번 괄호의 값

반응형

[BOJ] 2504번 괄호의 값

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

문제 접근

Stack을 이용해서 열린 괄호를 저장하고, 괄호가 닫힐 때 X값을 다시 스택에 저장한다.
괄호 속에 숫자가 있으면 그 숫자들을 다 더해서 해당 괄호 값을 곱해주었다.
그리고 스택을 Character 자료형으로 하면 괄호와 숫자를 구분하지 못하기 때문에, String으로 해서 이 경우를 해결했다.
코드가 너무 복잡하고 올바른 괄호가 아닌것을 검사하기가 까다로웠다...

Code

import java.util.Scanner;
import java.util.Stack;

public class BOJ2504 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        Stack<String> st = new Stack<>();
        int sum = 0;
        for(int i = 0; i<input.length(); i++){
            if(input.charAt(i) == '('){
                st.push("(");
            } else if(input.charAt(i) == '['){
                st.push("[");
            } else if(input.charAt(i)== ')'){
                int temp = 0;
                if(st.isEmpty()){
                    sum = -1;
                    break;
                }
                while(!st.isEmpty() && !st.peek().equals("(")){
                    String num = st.pop();
                    if(!Character.isDigit(num.charAt(0))){
                        sum = -1;
                        break;
                    }
                    temp += Integer.parseInt(num);
                }
                if(sum == -1|| st.isEmpty()) {
                    sum = -1;
                    break;
                }
                if(temp == 0) temp = 2;
                else temp = temp * 2;
                st.pop();
                st.push(String.valueOf(temp));
            } else if(input.charAt(i) == ']'){
                int temp = 0;
                if(st.isEmpty()){
                    sum = -1;
                    break;
                }
                while(!st.isEmpty() && !st.peek().equals("[")){
                    String num = st.pop();
                    if(!Character.isDigit(num.charAt(0))){
                        sum = -1;
                        break;
                    }
                    temp += Integer.parseInt(num);
                }
                if(sum == -1|| st.isEmpty()){
                    sum = -1;
                    break;
                }
                if(temp == 0) temp = 3;
                else temp = temp * 3;
                st.pop();
                st.push(String.valueOf(temp));
            }
        }
        if(sum == -1){
            sum = 0;
        } else {
            while(!st.isEmpty()){
                String num = st.pop();
                if(!Character.isDigit(num.charAt(0))){
                    sum = 0;
                    break;
                }
                sum += Integer.parseInt(num);
            }
        }
        System.out.print(sum);
    }
}
반응형