본문 바로가기
PS 문제 풀이/Baekjoon

[BOJ] 백준 2504 괄호의값

by 까망 하르방 2021. 6. 5.
반응형

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

Approach

스택을 이용하는 대표적인 문제이다.

괄호를 스택에 넣어서 올바른 괄호쌍을 맞추는지 확인한다.

[스택] Stack 이란?  

 

[스택] Stack 이란?

Stack 이란? 스택 (Stack) 특징을 가장 잘 나타내는 표현은 후입선출(Last In First Out, LIFO) 이다. ▶ 스택(Stack)은 삽입(push)과 삭제(pop)이 한쪽 끝에서만 일어나는 구조 가장 상단에 위치한 원소를 가리.

zoosso.tistory.com


import java.util.Scanner;

class Stack {
	int top;
	String[] stack;
	
	public Stack(int size) {
		top = -1;
		stack = new String[size];
	} // 스택 초기

	public void push(String value) {
		stack[++top] = value;
	}

	public String pop() {
		return stack[top--]; //아이템을 반환하고 top 감소 
	}
}

public class Main {
	public static void main(String[] args) {
		Stack judge_stack = new Stack(50);
		Stack st = new Stack(500);
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		
		for(int i=0; i<str.length(); i++){
	         if(str.charAt(i) == '(' || str.charAt(i) == '['){
	        	 judge_stack.push(Character.toString(str.charAt(i)));
	         }
	         else if(str.charAt(i) == ')'){
	            if(judge_stack.top == -1){
	               System.out.println(0);
	               return;
	            }
	            String temp = judge_stack.pop();
	            if(!temp.equals("(")){
	               System.out.println(0);
	               return;
	            }
	         }
	         else if(str.charAt(i) == ']'){
	            if(judge_stack.top == -1){
	               System.out.println(0);
	               return;
	            }
	            String temp = judge_stack.pop();
	            if(!temp.equals("[")){
	               System.out.println(0);
	               return;
	            }
	        }
	    }

		if(judge_stack.top != -1){
			System.out.println(0);
			return;
		}
		
		// 결과 계산
		int result = 0;
		int temp_result = 0;
		int last_result = 0;
		for(int i=0; i<str.length(); i++){
			if(str.charAt(i) == '('){
				if(str.charAt(i+1) == ')'){ 
					st.push("2");
					i++; // ()는 숫자로 처리 
				}
				else{
					st.push("(");
					st.push("2");
					st.push("*");
				}	
			}
			else if(str.charAt(i) == '[' ){
				if(str.charAt(i+1) == ']'){ 
					st.push("3");
					i++; // []는 숫자로 처리 
				}
				else{
					st.push("[");
					st.push("3");
					st.push("*");
				}
			}
			else if(str.charAt(i) == ')'){
				while(true){
					if(st.top == -1)
						break;
					String temp = st.pop();
					if(temp.equals("("))
						break;
					else if(temp.equals("*")){
						result = result * Integer.parseInt(st.pop());
					}
					else{
						result = result + Integer.parseInt(temp);
					}
				}
				if(st.top == -1){
                    // [()()()]와 같 경우를 처리하기 위해  
					last_result = last_result + result;  
					result = 0;
				}else{
					st.push(String.valueOf(result));
					result = 0;
				}
				
			}
			else if(str.charAt(i) == ']'){
				while(true){
					if(st.top == -1)
						break;
					String temp = st.pop();
					if(temp.equals("["))
						break;
					else if(temp.equals("*")){
						result = result * Integer.parseInt(st.pop());
					}
					else{
						result = result + Integer.parseInt(temp);
					}
				}
				if(st.top == -1){
                    // [()()()]와 같 경우를 처리하기 위해  
					last_result = last_result + result;  
					result = 0;
				}else{
					st.push(String.valueOf(result));
					result = 0;
				}
			}
		}
        
		while(st.top != -1){
			last_result = last_result + Integer.parseInt(st.pop());
            // ()()() 으로 이뤄졌을 때 혹시 result로 계산된 값이 있으면 마저 처리 
			if(st.top == -1)
            { 
				last_result = last_result + result;
			}
		}
		System.out.println(last_result);
	}
}

 

반응형

댓글