๋ฐ์ํ
[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 |