본문 바로가기

Algorithm/Algospot

[algospot]BRACKETS2

문제

 

https://algospot.com/judge/problem/read/BRACKETS2

3가지 괄호 () {} [] 가 섞인 문자열이 나온다. 같은종류의 괄호쌍들이 잘 열리고 닫혔는지 확인하는 문제

 

입력

10000개 미만의 () {} [] 가 섞인 문자열~

 

출력

올바르게 열리고 닫혔으면 YES 잘못 열리고 닫혔으면 NO

 

풀이

괄호가 열리는것을 계속 저장해야한다.제일 마지막에 열린것부터 닫아 나가야 하기때문이다.

문자열을 통해서 마지막에 붙여나가는방법도 있지만 이럴때 생각나는 것이 리눅스 공부할때 스택구조다.

열리는 괄호가 나오면 스택에 축하고 닫히는게 나오면 스택에서 하나pop한다음에 괄호쌍인지 비교하는 방법을 통해서 문제를 풀 수 있다.

package com.tutorial;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class BRACKETS2 {
    public static void main(String[] args)throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System. in));
        int cnt = Integer.parseInt(br.readLine());
        Stack < byte > st = new Stack<byte>();
        while (cnt -- > 0) {
            String a = br.readLine();
            byte[] b = a.getBytes();
            int i;
            for (i = 0; i < b.length; i ++) {
                if (b[i] == '(' || b[i] == '{' || b[i] == '[') {
                    st.push(b[i]);
                } else {
                    if (st.size() > 0) {
                        if (Math.abs(st.pop() - b[i]) > 2) {
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
            if (st.size() == 0 && b.length == i) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }
        }
    }
}

 

'Algorithm > Algospot' 카테고리의 다른 글

[algospot]DRAWRECT  (0) 2014.12.15
[algospot]FIXPAREN  (0) 2014.12.15
[algospot]HAMMINGCODE  (0) 2014.12.15
[algospot]WEIRD  (0) 2014.12.15
[algospot]URI  (0) 2014.12.15