๐ '(', '[' ๊ดํธ๋ง๋ค์ ๊ฒฝ์ฐ๋ฅผ ๋ชจ๋ ์ฐ๊ณ , ์ฌ๋ฐ๋ฅด์ง ์์ ๊ฒฝ์ฐ๋ ํ๋ํ๋ ์ฒดํฌํด์ค ์ฝ๋๋ ์๊ฐ์ด๊ณผ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.
๐ ๋ค๋ฅธ ๋ถ์ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํ์ฌ ์ฌ๋ฐ๋ฅด์ง ์์ ๊ฒฝ์ฐ๋ฅผ ๋ฏธ๋ฆฌ ํ์ธํ๊ณ , reverse, point ๋ณ์๋ฅผ ์ถ๊ฐํ์ฌ ์ฝ๋๋ฅผ ๊ฐ์ํํ์๋ค.
์๊ฐ ์ด๊ณผ ์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('');
let stack = [];
for (let i = 0; i < input.length; i++) {
if (input[i] === "]") {
if (stack.length !== 0) {
const top = stack[stack.length - 1];
if (top === "[") {
stack.pop();
stack.push(3);
} else if (top === "(") {
console.log(0);
return;
} else {
let sum = 0;
while (true) {
let top = stack.pop();
if (top === "(") {
console.log(0);
return;
} else if (top === "[") {
stack.push(3 * sum);
break;
} else {
sum += top;
}
}
}
} else {
console.log(0);
return;
}
} else if (input[i] === ")") {
if (stack.length !== 0) {
const top = stack[stack.length - 1];
if (top === "(") {
stack.pop();
stack.push(2);
} else if (top === "[") {
console.log(0);
return;
} else {
let sum = 0;
while (true) {
let top = stack.pop();
if (top === "[") {
console.log(0);
return;
} else if (top === "(") {
stack.push(2 * sum);
break;
} else {
sum += top;
}
}
}
} else {
console.log(0);
return;
}
} else {
stack.push(input[i]);
}
}
console.log(stack.reduce((a, b) => a + b, 0));
์ ๋ต ์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('');
let stack = [];
for (let i = 0; i < input.length; i++) {
let top = stack[stack.length - 1];
if (top === "[" && input[i] === "]") {
stack.pop();
} else if (top === "(" && input[i] === ")") {
stack.pop();
} else {
stack.push(input[i]);
}
}
if (stack.length !== 0) {
console.log(0);
return;
} else {
stack = [];
}
for (let i = 0; i < input.length; i++) {
const top = stack[stack.length - 1];
const reverse = input[i] === ")" ? "(" : "[";
const point = input[i] === ")" ? 2 : 3;
if (input[i] === "]" || input[i] === ")") {
if (top === reverse) {
stack.pop();
stack.push(point);
} else {
let sum = 0;
while (true) {
let top = stack.pop();
if (top === reverse) {
stack.push(point * sum);
break;
} else {
sum += top;
}
}
}
} else {
stack.push(input[i]);
}
}
console.log(stack.reduce((a, b) => a + b, 0));