BaekJoon 1541 잃어버린 괄호

이번 Posting에서는 백준 1541번 문제에 대한 것입니다.

이 문제는 아이디어를 생각하는 것은 어렵지 않지만 문자열을 잘라내는 것이 약간 까다로운 점이 있었습니다.

처음으로 등장하는 '-'(minus) 이전까지는 전부 +인 상태이기 때문에 전부 더해주는 형태가 되고 '-' 이후로는 양수들을 모두 음수로 바꾸어 더해주시면 됩니다.

코드는 다음과 같습니다.



 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
import java.util.Arrays;
import java.util.Scanner;

public class BaekJoon1541 {
    static String str;
    static char[] chars = new char[10];
    static String[] strs = new String[55];
    static String[] numbers = new String[55];
    static boolean isMinus;
    static int Answer, o, m, sLength, t;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        isMinus = false;Arrays.fill(numbers, "");
        str = sc.nextLine();o = 0;m = 0; t = 1;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '-' || str.charAt(i) == '+') {
                strs[t] = "" + str.charAt(i);t += 2;
                for (int j = 0; j < o; j++) {
                    numbers[m] += chars[j];
                }m++;o = 0;
            }else {
                chars[o++] = str.charAt(i);
            }
        }
        for (int i = 0; i < o; i++) {
            numbers[m] += chars[i];
        }m++;
        for (int i = 0; i < m; i++) {
            strs[i * 2] = numbers[i];
        }sLength = m * 2 - 1;
        Answer = Integer.parseInt(strs[0]);
        for (int i = 1; i < sLength; i++) {
            if (isMinus) {
                if (strs[i - 1].equals("+")) {
                    Answer -= Integer.parseInt(strs[i]);
                } else if (strs[i - 1].equals("-")) {
                    Answer -= Integer.parseInt(strs[i]);
                }
            }else {
                if (strs[i - 1].equals("+")) {
                    Answer += Integer.parseInt(strs[i]);
                }else if (strs[i - 1].equals("-")){isMinus = true;
                    Answer -= Integer.parseInt(strs[i]);
                }
            }
        }
        System.out.println(Answer);
    }
}

이 블로그의 인기 게시물

웹툰 무료로 볼 수 있는 사이트

BackJoon 1011, Fly me to the alpha centauri, 규칙 찾기 문제

BaekJoon 6591, 이항 쇼다운 조합문제