문제
https://www.acmicpc.net/problem/1541
1541번: 잃어버린 괄호
첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다
www.acmicpc.net
1. 접근 방식
문제 이해에 많이 헤맸다.
부호 '-' 부터 다음 '-'부호가 나오기 전까지 괄호를 치면 괄호안의 값들은 셈이 된 상태에서 음수로 변경 되기 때문에 가장 작은 값이 나올 수 있다.
그렇기 때문에 배열의 마지막부터 '-'를 탐색하면서 해당 값들을 빼주면 최소값이 나온다. 다만 마지막부터 탐색하기 때문에 앞쪽에 '+' 기호만 존재할 경우가 생기기 때문에 해당 값만 더해주면 된다.
2. 구현
*주의 사항
26번째 줄 split을 할 때 "+"로만 패턴을 보내면
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
이런 오류가 발생한다.
아마 자바에서 사용하는 특수기호 예약어인 경우에 백슬래쉬를 넣어서 구분해줘야 하기 때문인듯하다. [,],-,(,) 등의 특수 기호들도 같은 오류가 발생한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String equation = br.readLine();
int sum = 0;
for (int i=equation.length()-1; i>=0; i--) {
if (equation.charAt(i) == '-') {
String temp = equation.substring(i+1);
temp = temp.replace("+", " ");
String[] temArr = temp.split(" ");
for (int j=0; j<temArr.length; j++) {
sum -= Integer.parseInt(temArr[j]);
}
equation = equation.substring(0, i);
}
}
String temp = equation.toString();
String[] temArr = temp.split("\\+");
for (int i=0; i<temArr.length; i++) {
sum += Integer.parseInt(temArr[i]);
}
System.out.println(sum);
}
}
정리 : 어렵지 않았지만 다른 코드를 보니 더 깔끔하게 잘한 코드가 있어 아래에 첨부한다.
나와 같은 원리이지만 차이는 어차피 '-'부호에서 끊어야 하기 때문에 애초에 '-' 를 기준으로 split을 먼저 해주는게 차이점이다.
import java.util.Scanner;
public class P1541_잃어버린괄호 {
static int answer = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String example = sc.nextLine();
String[] str = example.split("-");
for (int i = 0; i < str.length; i++) {
int temp = mySum(str[i]);
if (i == 0)
answer = answer + temp; // 제일 앞에 것만 더해주고
else
answer = answer - temp; // 뒤에 부분은 더한 값들을 빼줌
}
System.out.println(answer);
}
static int mySum(String a) { // 나눠진 그룹의 더하기 연산 수행 함수
int sum = 0;
String temp[] = a.split("[+]");
for (int i = 0; i < temp.length; i++) {
sum += Integer.parseInt(temp[i]);
}
return sum;
}
}
출처 : https://github.com/doitcodingtestjava/answer/blob/main/%EA%B7%B8%EB%A6%AC%EB%94%94/P1541_%EC%9E%83%EC%96%B4%EB%B2%84%EB%A6%B0%EA%B4%84%ED%98%B8.java
'백준' 카테고리의 다른 글
백준 1016번 자바 ☆ (0) | 2023.02.21 |
---|---|
백준 1747번 자바 (0) | 2023.02.20 |
백준 1931번 자바☆ (0) | 2023.02.15 |
백준 1456번 자바 ☆ (0) | 2023.02.15 |
백준 1929번 자바 (0) | 2023.02.15 |