알고리즘 문제/백준(BOJ)
[백준 2504번] 괄호의 값 :: 늦깎이 IT
집돌이탈출
2019. 3. 22. 18:30
1. 입력으로 주어지는 문자열의 길이가 홀수라면 0을 리턴한다.
2. 여는 괄호는 스택에 넣는다.
3. 닫는 괄호가 나오면 다음을 수행한다. (설명은 [, ] 괄호에 대해서만 한다.)
- 스택에서 pop 한 값이 닫는 괄호( ] )와 쌍인 여는 괄호라면( [ ) 3을 스택에 넣는다.
- 스택에서 pop 한 값이 닫는 괄호( ] )와 쌍이 아닌 여는 괄호라면 ( ( ) 0을 리턴한다.
- 스택에서 pop 한 값이 숫자라면, 닫는 괄호( ] )와 쌍인 여는 괄호( [ )가 나올때 까지 pop한다. 이 과정에서 pop하는 숫자들은 모두 더해줘야만 한다. 예) [ 2 2 2 ] = (2 + 2 + 2) * 3 = 18 임을 인지한다.
- 스택을 모두 비울때 까지 여는 괄호를 못찾았다면 0을 리턴한다.
- 반복한다.
[소스 코드]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class Main { static int N; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; public static void main(String[] args) throws IOException { String input = br.readLine(); System.out.println(isPossible(input, input.length())); } public static int isPossible(String input, int length) { if (length % 2 != 0) return 0; Stack<String> stack = new Stack<>(); for (int i = 0; i < length; i++) { String op = input.charAt(i) + ""; if (op.equals("(") || op.equals("[")) { stack.push(op); } else if (op.equals(")")) { if (!check(stack, "(", "[")) return 0; } else if (op.equals("]")) { if (!check(stack, "[", "(")) return 0; } } int result = 0; while (!stack.isEmpty()) result += Integer.parseInt(stack.pop()); return result; } public static boolean check(Stack<String> stack, String yesBracket, String noBracket) { int sum = 0; int mul = (yesBracket == "(") ? 2 : 3; while (!stack.isEmpty()) { String pop = stack.pop(); if (pop.equals(noBracket)) return false; else if (pop.equals(yesBracket)) { sum = (sum == 0) ? 1 : sum; stack.push(Integer.toString(sum * mul)); return true; } else { sum += Integer.parseInt(pop); } } return false; } } | cs |