알고리즘

백준 1541번 잃어버린 괄호 (JAVA)

박카스마시며코딩 2022. 6. 27. 10:29

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

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

 

저는 해당 문제를 그리디적으로 문제를 해결하였습니다.

저는 +를 먼저 연산하고 -를 나중에 연산하여 문제를 해결하였습니다.

이후 첫번째 값이면 결과값을 초기화하고, 첫번째 값이 아니라면 결과값에서 각각의 값을 뺴 결과를 도출하였습니다.

 

package BOJ.greedy;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.function.Function;

public class BOJ_1541 {
    private static final int NOT_VALID = 987654321;
    private static final String PLUS = "\\+";
    private static final String MINUS = "-";
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String command = br.readLine();
        String[] deleteMinus = command.split(MINUS);
        int result = NOT_VALID;
        Function<String,Integer> stoi = Integer::parseInt;
        for(String s : deleteMinus){
            int sum = 0;
            String[] temps = s.split(PLUS);
            sum += Arrays.stream(temps).mapToInt(i -> stoi.apply(i)).sum();
            if(result == NOT_VALID){
                result = sum;
            }else{
                result -= sum;
            }
        }
        System.out.println(result);
    }
}