알고리즘

백준 4889번 안정적인 문자열 (JAVA)

박카스마시며코딩 2023. 2. 27. 14:10

https://www.acmicpc.net/problem/4889

 

4889번: 안정적인 문자열

입력은 여러 개의 데이터 세트로 이루어져 있다. 각 데이터 세트는 한 줄로 이루어져 있다. 줄에는 여는 괄호와 닫는 괄호만으로 이루어진 문자열이 주어진다. 문자열의 길이가 2000을 넘는 경우

www.acmicpc.net

 

 

 

package BOJ.etc;

import java.awt.print.Pageable;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BOJ_4889 {
    private static final char OPEN = '{';
    private static final char CLOSE = '}';
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int num = 1;
        while(true){
            String command = br.readLine();
            if(command.charAt(0) == '-'){
                break;
            }
            int cnt = 0;
            int result = 0;
            for(int i = 0 ; i < command.length() ; i++){
                char ch = command.charAt(i);
                if(ch == OPEN){
                    cnt++;
                }else {
                    cnt--;
                }
                if(cnt < 0){
                    result++;
                    cnt += 2;
                }
            }
            if(cnt > 0){
                result += cnt / 2;
            }
            System.out.println(num + ". " + result);
            num++;
        }
    }
}