반응형
[BOJ] 2504번 괄호의 값
https://www.acmicpc.net/problem/2504
문제 접근
Stack을 이용해서 열린 괄호를 저장하고, 괄호가 닫힐 때 X값을 다시 스택에 저장한다.
괄호 속에 숫자가 있으면 그 숫자들을 다 더해서 해당 괄호 값을 곱해주었다.
그리고 스택을 Character 자료형으로 하면 괄호와 숫자를 구분하지 못하기 때문에, String으로 해서 이 경우를 해결했다.
코드가 너무 복잡하고 올바른 괄호가 아닌것을 검사하기가 까다로웠다...
Code
import java.util.Scanner;
import java.util.Stack;
public class BOJ2504 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
Stack<String> st = new Stack<>();
int sum = 0;
for(int i = 0; i<input.length(); i++){
if(input.charAt(i) == '('){
st.push("(");
} else if(input.charAt(i) == '['){
st.push("[");
} else if(input.charAt(i)== ')'){
int temp = 0;
if(st.isEmpty()){
sum = -1;
break;
}
while(!st.isEmpty() && !st.peek().equals("(")){
String num = st.pop();
if(!Character.isDigit(num.charAt(0))){
sum = -1;
break;
}
temp += Integer.parseInt(num);
}
if(sum == -1|| st.isEmpty()) {
sum = -1;
break;
}
if(temp == 0) temp = 2;
else temp = temp * 2;
st.pop();
st.push(String.valueOf(temp));
} else if(input.charAt(i) == ']'){
int temp = 0;
if(st.isEmpty()){
sum = -1;
break;
}
while(!st.isEmpty() && !st.peek().equals("[")){
String num = st.pop();
if(!Character.isDigit(num.charAt(0))){
sum = -1;
break;
}
temp += Integer.parseInt(num);
}
if(sum == -1|| st.isEmpty()){
sum = -1;
break;
}
if(temp == 0) temp = 3;
else temp = temp * 3;
st.pop();
st.push(String.valueOf(temp));
}
}
if(sum == -1){
sum = 0;
} else {
while(!st.isEmpty()){
String num = st.pop();
if(!Character.isDigit(num.charAt(0))){
sum = 0;
break;
}
sum += Integer.parseInt(num);
}
}
System.out.print(sum);
}
}
반응형
'Algorithm' 카테고리의 다른 글
[Algorithm/Java][백준] 1700번 멀티탭 스케줄링 (0) | 2022.05.17 |
---|---|
[Algorithm/Java][백준] 1062번 가르침 (0) | 2022.05.16 |
[Algorithm/Java][백준] 1987번 알파벳 (0) | 2022.05.08 |
[Algorithm/Java][백준] 2467번 용액 (0) | 2022.05.03 |
[Algorithm/Java][백준] 12852번 1로 만들기 2 (0) | 2022.05.01 |