https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일 X
www.acmicpc.net
📌 작성한 코드 1
// 2504
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "Beakjoon/Gold/test.txt";
let input = fs.readFileSync(filePath).toString().trim().split("");
const solution = () => {
if (input[0] === ")" || input[0] === "]") {
console.log(0);
return;
}
const stack = [input[0]];
const numStack = [];
const countStack = [0];
for (let i = 1; i < input.length; i++) {
if (input[i] === "[" || input[i] === "(") {
countStack.push(0);
stack.push(input[i]);
} else if (stack[stack.length - 1] === "[" && input[i] === "]") {
stack.pop();
let count = countStack.pop();
let sum = 0;
if (count === 0) numStack.push(3);
else {
while (count--) {
sum += numStack.pop();
}
numStack.push(sum * 3);
}
if (countStack.length) countStack[countStack.length - 1] += 1;
else countStack[0] = 1;
} else if (stack[stack.length - 1] === "(" && input[i] === ")") {
stack.pop();
let count = countStack.pop();
let sum = 0;
if (count === 0) numStack.push(2);
else {
while (count--) {
sum += numStack.pop();
}
numStack.push(sum * 2);
}
if (countStack.length) countStack[countStack.length - 1] += 1;
else countStack[0] = 1;
} else {
console.log(0);
return;
}
}
if (stack.length) console.log(0);
else console.log(numStack.reduce((acc, cur) => acc + cur, 0));
};
solution();
📌 풀이

📌작성한 코드 2
const stack = [];
let plus = 1;
let answer = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] === "(") {
stack.push(input[i]);
plus *= 2;
}
if (input[i] === "[") {
stack.push(input[i]);
plus *= 3;
}
if (input[i] === ")") {
if (!stack.length || stack[stack.length - 1] !== "(") {
answer = 0;
break;
}
if (input.length && input[i - 1] === "(") {
answer += plus;
}
stack.pop();
plus /= 2;
}
if (input[i] === "]") {
if (!stack.length || stack[stack.length - 1] !== "[") {
answer = 0;
break;
}
if (input.length && input[i - 1] === "[") {
answer += plus;
}
stack.pop();
plus /= 3;
}
}
stack.length > 0 ? console.log(0) : console.log(answer);
📌 풀이
참고 ) https://velog.io/@miloul/%EB%B0%B1%EC%A4%80-2504-%EA%B4%84%ED%98%B8%EC%9D%98-%EA%B0%92-Javascript

📌 테스트케이스
https://www.acmicpc.net/board/view/62519
✅ 성공

'알고리즘 > 백준' 카테고리의 다른 글
| [JavaScript/BFS] 백준 골드 3 : 2206 - 벽 부수고 이동하기 (1) | 2024.01.25 |
|---|---|
| [JavaScript/BFS] 백준 골드 4 : 4179 - 불! (2) | 2024.01.24 |
| [JavaScript/Stack] 백준 실버 2 : 10799 - 쇠막대기 (0) | 2024.01.23 |
| [JavaScript/Stack] 백준 실버 4 : 3986 - 좋은 단어 (0) | 2024.01.23 |
| [JavaScript/Stack] 백준 실버 4 : 4949 - 균형잡힌 세상 (0) | 2024.01.23 |