ALGORITHM/BOJ
[BOJ] 1541 잃어버린 괄호
0298
2022. 7. 4. 21:30
https://www.acmicpc.net/problem/1541
1541번: 잃어버린 괄호
첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다
www.acmicpc.net
2022-07-04
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
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main1541 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
String[] str = st.nextToken().split("-");
Queue<Integer> s = new LinkedList<>();
for(int i = 0; i < str.length; i++) {
if(str[i].contains("+")) {
String[] tmp = str[i].split("\\+");
int num = 0;
for(int j = 0; j < tmp.length; j++) {
if(!tmp[j].equals("+")) {
num += Integer.parseInt(tmp[j]);
}
}
s.offer(num);
} else s.offer(Integer.parseInt(str[i]));
}
int answer = s.poll();
while(!s.isEmpty()) answer -= s.poll();
System.out.println(answer);
}
}
|
cs |
#문제풀이
1) " - " 를 기준으로 split 하고
2) 돌면서 " + " 를 포함하고 있는 문자열을 발견하면 다 더해서 queue에 넣어놓고
3) " + " 없으면 그냥 queue에 포함
4) 제일 앞 숫자 poll하고, 그 뒤에 while문 돌면서 모든 숫자 빼기