https://www.acmicpc.net/problem/10799
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 | import java.util.Scanner; class Stack{ private int[] stack; private int top; private int defaultData = -999; Stack(int lenght){ this.stack = new int[lenght]; for(int i = 0; i<this.stack.length; i++){ this.stack[i] = defaultData; } this.top = 0; } void push(int data){ this.stack[this.top] = data; this.top++; // System.out.println("push: "+top); } int pop(){ this.top--; int data = this.stack[top]; this.stack[top] = defaultData; // System.out.println("pop: "+top); return data; } int getSize(){ return this.top; } } public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); char[] c = str.toCharArray(); Stack st = new Stack(c.length); int result = 0; for(int i = 0; i<c.length; i++){ if(c[i] == '('){ st.push(i); // 여는 괄호의 index값을 stack에 넣는다. }else{ //닫는 괄호에서 if(i - st.pop() == 1) { // 현재 i의 값(닫는 괄호의 index)와 마지막으로 넣은 여는 괄호의 index의 차이가 1이라면 // System.out.println("i-x = 1"); result += st.getSize(); // 현재 stack의 사이즈를 result에 더해준다. } else{ // 이 부분 조심. 위의 if중에 함수 실행하는 명령어가 포함되어 있으면 else문에서도 함수가 실행됨. (현재: st.pop()이 실행됬음.) // System.out.println("i-x != 1"); // st.pop(); result+=1; } } } System.out.println(result); } } | cs |
'알고리즘 > 백준 알고리즘' 카테고리의 다른 글
[code.plus 알고리즘 기초] no. 11727 (0) | 2019.01.17 |
---|---|
[code.plus 알고리즘 기초] no. 11726 (0) | 2019.01.16 |
[code.plus 알고리즘 기초]no. 1463 (0) | 2019.01.16 |
[code.plus 알고리즘 기초]no. 1158 (0) | 2019.01.14 |
[code.plus 알고리즘 기초]no. 9012 (0) | 2019.01.13 |