티스토리 뷰
https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일 X
www.acmicpc.net
다 처리했는데, 괄호가 남아있으면 올바른 괄호열이 아니니까 0을 출력해야한다.
TC
[()]]
const fs = require('fs');
const input = fs.readFileSync('./dev/stdin').toString().trim();
class Node {
constructor(item) {
this.item = item;
this.next = null;
}
}
class Stack {
constructor() {
this.topOfStack = null;
this.length = 0;
}
push(item) {
const node = new Node(item);
if (this.topOfStack != null) {
node.next = this.topOfStack;
}
this.topOfStack = node;
this.length += 1;
}
pop() {
if (this.length == 0) return '';
const popItem = this.topOfStack;
this.topOfStack = popItem.next;
this.length -= 1;
return popItem.item;
}
size() {
return this.length;
}
empty() {
if (this.length == 0) return true;
else return false;
}
top() {
if (this.length == 0) return false;
return this.topOfStack.item;
}
print() {
const test = [];
let pointer = this.topOfStack;
while (pointer != null) {
test.unshift(pointer.item);
pointer = pointer.next;
}
console.log(test.join(''));
}
calc() {
let answer = 0;
while (!this.empty()) {
const value = this.pop();
if (typeof value != 'number') {
console.log(0);
process.exit();
}
answer += value;
}
return answer;
}
}
let answer = 0;
const stack = new Stack();
for (let i = 0; i < input.length; i++) {
const b = input[i];
switch (b) {
case '(':
stack.push(b);
break;
case ')':
{
const nums = [];
while (true) {
const top = stack.top();
if (top == '(') {
stack.pop();
if (nums.length == 0) {
stack.push(2);
} else {
stack.push(2 * nums.reduce((r, v) => r + v, 0));
}
break;
} else if (typeof top === 'number') {
nums.push(stack.pop());
} else {
console.log(0);
process.exit();
}
if (stack.empty()) {
console.log(0);
process.exit();
}
}
}
break;
case '[':
stack.push(b);
break;
case ']':
{
const nums = [];
while (true) {
const top = stack.top();
if (top == '[') {
stack.pop();
break;
} else if (typeof top === 'number') {
nums.push(stack.pop());
} else {
console.log(0);
process.exit();
}
if (stack.empty()) {
console.log(0);
process.exit();
}
}
if (nums.length == 0) {
stack.push(3);
} else {
stack.push(3 * nums.reduce((r, v) => r + v, 0));
}
}
break;
}
}
console.log(stack.calc());
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 2493번: 탑 (0) | 2023.06.20 |
---|---|
Node.js) 백준 2525번: 오븐 시계 (0) | 2023.06.20 |
Node.js) 백준 10799번: 쇠막대기 (0) | 2023.06.18 |
Node.js) 백준 5397번: 키로거 (0) | 2023.06.18 |
Node.js) 백준 1475번: 방 번호 (0) | 2023.06.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 개발자면접
- 그래프
- 서버개발
- node.js
- 로드나인
- create databases;
- MOD
- DB 생성
- 다이나밍프로그래밍
- 투포인터 연습
- 면접질문
- 면접비
- create db
- 최소공통조상
- 은둔청년체험
- BFS
- 투포인터
- MySQL
- 동적프로그래밍
- 서버점검
- 다이나믹프로그래밍
- 롱베케이션
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함