전공공부
[BOJ_2504] 괄호의 값 본문
설명
이번 문제는 쉽게 풀지 못해서 이전에 풀었던 히스토리를 가지고 풀었다. 우선 스택 수열때 처럼 카운팅 하는 방식을 버리고 애초에 괄호의 닫힌 괄호를 처음 push 할 때 넣어버려서 닫힌 괄호가 들어 올 때 검증 체크를 진행하고 이에 따라서, 괄호의 값을 넣어준다.
코드
package Data_Structure;
import java.util.*;
import java.io.*;
public class BOJ_2504 {
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = in.readLine();
Stack<String> st = new Stack<>();
char tmp = ' ';
boolean isAble = true;
for(int i = 0; i < str.length(); i++){
String s = str.substring(i,i+1);
if("(".equals(s)){
st.push(")");
continue;
}
if("[".equals(s)){
st.push("]");
continue;
}
int cnt = 0;
while(true) {
// 아직본인 괄호가 나오지 않았는데 스택이 비었다는 뜻 유효하지 않은 괄호 문자열
if(st.isEmpty()) {
isAble = false;
break;
}
if(isNumber(st.peek())) {
cnt += Integer.parseInt(st.pop());
}else {
if(isVPS(s, st.peek())) {
st.pop();
int t = (")".equals(s)) ? 2:3;
if(cnt == 0) {
st.push(String.valueOf(t));
}else {
st.push(String.valueOf(t * cnt));
}
break;
}else {
isAble = false;
break;
}
}
}
if(!isAble) break;
}
int result = 0;
// 스택이 빌때까지 POP한다.
//정상적인 괄호 문자열이라면 스택에는 숫자만 들어 있어야 한다.
while(!st.isEmpty()) {
if(isNumber(st.peek())) {
result += Integer.parseInt(st.pop());
}else {
isAble = false;
break;
}
}
if(isAble) System.out.println(result);
else System.out.println(0);
}
public static boolean isVPS(String c, String target) {
if(c.equals(target)) return true;
return false;
}
// 두 괄호가 아니면 무조건 숫자이다.
public static boolean isNumber(String str) {
if(str.equals(")") || str.equals("]")) return false;
return true;
}
}
'Study > Problem Solving' 카테고리의 다른 글
[BOJ_4358] 생태학 (0) | 2023.10.31 |
---|---|
[BOJ_11279] 최대 힙 (1) | 2023.10.30 |
[BOJ_1874] 스택 수열 (1) | 2023.10.28 |
[BOJ_14425] 문자열 집합 (1) | 2023.10.26 |
[BOJ_1620] 나는야 포켓몬 마스터 이다솜 (0) | 2023.10.25 |