본문 바로가기

Algorithm/Algospot

[algospot]FIXPAREN

문제

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

또 괄호닫기 문제다. 이번에는 괄호의 우선순위가 있고 우선순위에 맞게  괄호쌍을 변경해줘야한다.

입력된 괄호문자열이 (}고  {(<[ 가 우선순위라면 출력값이 {} 가 되어야 한다.

 

입력

100글자를 넘지 않는 문자열이 입력된다.

 

출력

우선순위대로 바뀐 문자열

 

풀이

일단 입력값을 받은뒤에 우선순위대로 괄호의 순서를 다시 재배치한다. 이전에 BRACKETS2문제를 풀때처럼

여는 괄호면 스택에 넣어주고 닫는 괄호가 나왔을때 우선순위로 비교해서 문자열을 처리한다.

 

package com.tutorial;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class FIXPAREN {
    private static char[] lp = {
        '(',
        '{',
        '[',
        '<'
    };
    private static char[] rp = {
        ')',
        '}',
        ']',
        '>'
    };
    private static char[] b;
    private static char[] p;
    public static void main(String[] args)throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System. in));
        int cnt = Integer.parseInt(br.readLine());
        while (cnt -- > 0) {
            String[] a = br.readLine().split(" ");
            b = a[0].toCharArray();
            p = a[1].toCharArray();
            int left = 0;
            char temp;
            Stack < Integer > s = new Stack<Integer>();
            for (int i = 0; i < p.length; i ++) {
                for (int j = 0; j < p.length; j ++) {
                    if (p[i] == lp[j]) {
                        temp = lp[j];
                        lp[j] = lp[i];
                        lp[i] = temp;
                        temp = rp[j];
                        rp[j] = rp[i];
                        rp[i] = temp;
                    }
                }
            }
            for (int i = 0; i < a[0].length(); i ++) {
                if (b[i] == lp[0] || b[i] == lp[1] || b[i] == lp[2] || b[i] == lp[3]) {
                    s.push(i);
                } else {
                    left = s.pop();
                    if (!((Math.abs(b[i] - b[left])) < 3)) {
                        for (int j = 0; j < 4; j ++) {
                            if (b[i] == rp[j] || b[left] == lp[j]) {
                                b[i] = rp[j];
                                b[left] = lp[j];
                                break;
                            }
                        }
                    }
                }
            }
            System.out.println(b);
        }
    }
}

 

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

[algospot]Ratio  (0) 2014.12.21
[algospot]DRAWRECT  (0) 2014.12.15
[algospot]BRACKETS2  (0) 2014.12.15
[algospot]HAMMINGCODE  (0) 2014.12.15
[algospot]WEIRD  (0) 2014.12.15