알고리즘문제풀이/백준

[BOJ]2504_괄호의값_Java

초보개발자.. 2021. 10. 16. 16:27

--문제--

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

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.  만일

www.acmicpc.net

--문제접근--

괄호 문제의 경우 스택을 이용하여 푸는데 어떻게 적용할지 생각이 나지않아 풀이 를 보고 이해하였습니다.

풀이참고는

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=yongyos&logNo=221454435252 여기를 참고하였습니다.

--코드--

package 준비운동;

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

public class BOJ_2504_괄호의값 {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		String str=sc.next();
		int mul=1, result=0;
		Stack<Character> stack =new Stack<>();
		boolean check=false;
		for(int i=0;i<str.length();i++) {
			switch(str.charAt(i)) {
			case '(':
				stack.push('(');
				mul*=2;
				break;
			case '[':
				stack.push('[');
				mul*=3;
				break;
			case ')':
				if(stack.isEmpty()||stack.peek()!='(') {
					result=0;
					check=true;
					break;
				}
				if (str.charAt(i - 1) == '(') result += mul;
				stack.pop();
				mul /= 2;
				break;

			case ']':
				if(stack.isEmpty()||stack.peek()!='[') {
					result=0;
					check=true;
					break;
				}
				if (str.charAt(i - 1) == '[') result += mul;
				stack.pop();
				mul /= 3;
				break;

			}
		}
		if(check||!stack.isEmpty())System.out.println(0);
		else System.out.println(result);
	}

}