다시 풀어보기..
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class Main { private void solve(){ String[] array = sc.readLine().split(""); Stack<String> stack = new Stack<>(); int sum = 0; int check = 0; for (int i = 0; i < array.length; i++) { if (check == -1) { System.out.println(0); return; } if (array[i].equals("(") || array[i].equals("[")) { stack.push(array[i]); } else { if (stack.isEmpty()) { System.out.println(0); return; } if (array[i].equals(")")) { if (stack.peek().equals("(")) { stack.pop(); stack.push("2"); } else { check = stackInnerLoop(stack, "[", "(", 2); } } else { if (stack.peek().equals("[")) { stack.pop(); stack.push("3"); } else { check = stackInnerLoop(stack, "(", "[", 3); } } } } // 최종 스택 안에는 정수들만 존재한다. // 괄호가 있을 시 올바르지 않은 문자열 while (!stack.isEmpty()) { if (stack.peek().equals("(") || stack.peek().equals(")") || stack.peek().equals("[") || stack.peek().equals("]")) { System.out.println(0); return; } sum += Integer.parseInt(stack.pop()); } System.out.println(sum); } private int stackInnerLoop(Stack<String> stack, String str1, String str2, int value) { int result = 0; while(!stack.isEmpty()){ String top = stack.peek(); if(top.equals(str1)){ return -1; }else if(top.equals(str2)){ stack.pop(); result *= value; stack.push(String.valueOf(result)); break; }else{ result += Integer.parseInt(stack.pop()); } } return result; } public static void main(String[] args) throws IOException { sc.init(); new Main().solve(); } static class sc{ private static BufferedReader br; static void init(){ br = new BufferedReader(new InputStreamReader(System.in)); } static String readLine(){ try{ return br.readLine(); }catch(IOException e){} return null; } } }//http://mygumi.tistory.com/175
'알고리즘(Java) > 스택' 카테고리의 다른 글
백준알고리즘 9012번 괄호 (0) | 2017.11.16 |
---|---|
알고리즘(스택 수열)-★ (0) | 2017.11.15 |