공부기록/자바스크립트 코딩테스트

[백준/JS] 1874 스택 수열

_우지 2022. 6. 29. 00:25

문제링크

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

 

문제풀이

const fs = require("fs");

BOJkey = true;

let input = fs
  .readFileSync(BOJkey ? "./자바스크립트로/1874/input.txt" : "./dev/stdin")
  .toString()
  .trim()
  .split("\n");
let result = [];
let n = input[0];
let stack = [];
let count = 0;
for (let i = 1; i <= n; i++) {
  while (true) {
    if (count > n) break;
    if (stack.length > 0 && stack[stack.length - 1] === +input[i]) {
      stack.pop();
      result.push("-");
      break;
    } else {
      count++;
      stack.push(count);
      result.push("+");
    }
  }
}
if (count > n) console.log("NO");
else console.log(result.join("\n"));