[BOJ] 스택 문제들 다시풀기

레몬커드요거트·2026년 4월 14일

코딩테스트준비

목록 보기
38/66
post-thumbnail

10828. 스택

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString()
  .trim()
  .split("\n");

const N = input[0];

const stackArr = [];
function pushProgram(line) {
  let target = Number(line.split(" ")[1]);
  stackArr.push(target);
}

function popProgram() {
  let target = stackArr.pop();
  console.log(target !== undefined ? target : -1);
}

function sizeProgram() {
  console.log(stackArr.length);
}

function emptyPropgram() {
  console.log(stackArr.length == 0 ? 1 : 0);
}

function topProgram() {
  if (stackArr.length == 0) {
    console.log(-1);
  } else {
    let target = stackArr[stackArr.length - 1];
    console.log(target);
  }
}

for (let i = 1; i <= N; i++) {
  line = input[i];
  command = line.split(" ")[0];
 
  if (command == "push") {
    pushProgram(line);
  } else if (command == "pop") {
    popProgram();
  } else if (command == "size") {
    sizeProgram();
  } else if (command == "empty") {
    emptyPropgram();
  } else if (command == "top") {
    topProgram();
  }
}

10773. 제로

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "dev/stdin" : "input.txt")
  .toString()
  .trim()
  .split("\n");

const K = input[0];
const stackArr = [];
let sum = 0;
for (let i = 1; i <= K; i++) {
  let n = Number(input[i]);
  if (n === 0) {
    let target = stackArr.pop();
    sum -= target;
  } else {
    stackArr.push(n);
    sum += n;
  }
}

console.log(sum);

9012. 괄호

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString()
  .trim()
  .split("\n");

T = input[0];

function isVPS(line) {
  value = line.split("");
  let cnt = 0;
  // console.log(value);
  for (let i = 0; i < value.length; i++) {
    if (value[i] === ")" && cnt === 0) {
      return (cnt = -1);
    }

    if (value[i] === "(") {
      cnt += 1;
    } else if (value[i] === ")") {
      cnt -= 1;
    }
  }
  return cnt;
}

for (let i = 1; i <= T; i++) {
  line = input[i];
  //console.log(isVPS(line));
  console.log(isVPS(line) === 0 ? "YES" : "NO");
}

4949. 균형잡힌 세상

실패코드1

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString();

// 온점(.) 뒤에 공백이나 줄바꿈이 오는 패턴을 기준으로 나누되, 온점은 유지합니다.
// (단, 문제 특성상 ' .\n' 같은 구조가 있을 수 있어 trim()과 조합이 필요합니다.)
const sentences = input.split(/(?<=\.)/);

function isBalanceSentence(line) {
  let smallPS = 0;
  let bigPs = 0;
  for (const char of line) {
    if (char === "[") {
      bigPs += 1;
    } else if (char === "]") {
      if (bigPs == 0) {
        return "no";
      }
      bigPs -= 1;
    } else if (char === "(") {
      smallPS += 1;
    } else if (char === ")") {
      if (smallPS == 0) {
        return "no";
      }
      smallPS -= 1;
    }
  }
  if (bigPs === 0 || smallPS === 0) {
    return "yes";
  }
}

for (let str of sentences) {
  const sentence = str.trim();
  console.log(sentence);
  if (sentence === ".") {
    console.log("yes");
  } else {
    console.log(isBalanceSentence(sentence));
  }
}
Help( I[m being held prisoner in a fortune cookie factory)].
>> yes

위의 경우에 대해서 괄호 닫히는 순서가 지켜지지 않았으므로 no 가 되어야하는데 관련 로직이 없음

실패코드2

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString();

// 온점(.) 뒤에 공백이나 줄바꿈이 오는 패턴을 기준으로 나누되, 온점은 유지합니다.
// (단, 문제 특성상 ' .\n' 같은 구조가 있을 수 있어 trim()과 조합이 필요합니다.)
const sentences = input.split(/(?<=\.)/);

function isBalanceSentence(line) {
  const stack = [];
  for (const char of line) {
    if (char === "(" || char === "[") {
      stack.push(char);

    } else if (char === ")") {
      if (stack.length > 0 && stack[stack.length - 1] === "(") {
        stack.pop();
      } else {
        return "no";
      }
    } else if (char === "]") {
      if (stack.length > 0 && stack[stack.length - 1] === "[") {
        stack.pop();
      } else {
        return "no";
      }
    }
  }
  return stack.length === 0 ? "yes" : "no";
}

for (let str of sentences) {
  const sentence = str.trim();
  // console.log(sentence);
  if (sentence === ".") {
    console.log("yes");
  } else {
    console.log(isBalanceSentence(sentence));
  }
}
 . 
>> yes
.
>> 출력없이 break

문장 가장 오른쪽에 대해서만 trim처리 필요

성공코드

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString()
  .split("\n");

function isBalanceSentence(line) {
  const stack = [];
  for (const char of line) {
    if (char === "(" || char === "[") {
      stack.push(char);
    } else if (char === ")") {
      if (stack.length > 0 && stack[stack.length - 1] === "(") {
        stack.pop();
      } else {
        return "no";
      }
    } else if (char === "]") {
      if (stack.length > 0 && stack[stack.length - 1] === "[") {
        stack.pop();
      } else {
        return "no";
      }
    }
  }
  return stack.length === 0 ? "yes" : "no";
}

for (let str of input) {
  if (str === ".") break;
  console.log(isBalanceSentence(str));
}

1874. 스택수열

아이디어 스케치

수열: 4; 3; 6; 8; 7; 5; 2; 1;

push: 1 2 3 4
pop: 4 3
스택: 1 2

push: 1 2 5 6
pop: 4 3 6
스택: 1 2 5

push: 1 2 5 7 8
pop: 4 3 6 8 7 5 2 1
스택:

실패코드

const n = input[0];
const stack = [];
const numlistIdx = 1;
const result = [];

for (let i = 1; i <= n; i++) {
  while (numlistIdx <= n) {
    if (stack[stack.length - 1] === input[numlistIdx]) {
      stack.push(i);
      result.push("+");
      stack.pop();
      result.push("-");
      numlistIdx++;
    } else {
      stack.push(i);
      result.push("+");
    }
  }
  if (i === n && numlistIdx > n) {
    result.push("-1");
  }
}

if (result[result.length - 1] === "-1") {
  console.log("NO");
} else {
  for (const char of result) {
    console.log(char + "\n");
  }
}
/Users/shinsujin/Desktop/Coding_Test/1874.js:22
      stack.push(i);
            ^

RangeError: Invalid array lengt

RangeError: Invalid array lengthwhile 루프가 무한 반복되면서 메모리를 다 써버림

발상의 전환

1부터 n까지의 숫자를 기준으로 순회하는 것이 아니라,
수열의 각 숫자를 ‘해결해야 할 타겟’으로 설정하여 수열의 인덱스를 기준으로 순회한다.

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "input.txt")
  .toString()
  .trim()
  .split("\n");

const n = Number(input[0]);
const targetSequence = input.slice(1).map(Number);

const stack = [];
const result = [];

let currentNum = 1;
let possible = true;

for (let i = 0; i < n; i++) {
  const target = targetSequence[i];
  while (currentNum <= target) {
    stack.push(currentNum);
    result.push("+");
    currentNum++;
  }
  if (stack[stack.length - 1] === target) {
    stack.pop();
    result.push("-");
  } else {
    possible = false;
    break;
  }
}

if (possible != true) {
  console.log("NO");
} else {
  console.log(result.join("\n"));
}
profile
비요뜨 최고~

0개의 댓글