[백준/9012] 괄호

문제

https://www.acmicpc.net/problem/9012

 

정답 코드1

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

class Stack {
  #array;

  constructor(array = []) {
    this.#array = array;
  }

  push(value) {
    return this.#array.push(value);
  }

  pop() {
    if (this.#array.length === 0) {
      return -1;
    }
    return this.#array.pop();
  }

  size() {
    return this.#array.length;
  }

  empty() {
    return this.#array.length === 0 ? 1 : 0;
  }

  top() {
    if (this.#array.length === 0) {
      return -1;
    } else {
      return this.#array[this.#array.length - 1];
    }
  }
}

function solution(input) {
  let result = [];

  for (let i = 1; i <= input[0]; i++) {
    const stack = new Stack();
    let isYes = true;
    for (let j = 0; j < input[i].length; j++) {
      if (input[i][j] === "(") {
        stack.push(input[i][j]);
      } else {
        if (stack.pop() === -1) {
          isYes = false;
          break;
        }
      }
    }

    if (stack.size() !== 0) {
      isYes = false;
    }
    isYes ? result.push("YES") : result.push("NO");
  }
  return result;
}

console.log(solution(input).join("\n"));

백준 스택 문제 풀었을 때 직접 만든 Stack 클래스를 활용했다. 물론 그냥 배열 사용하면 코드가 짧아진다. 😅

 

정답 코드2

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

function solution(input) {
  const results = [];

  for (let i = 1; i <= input[0]; i++) {
    let count = 0;
    let isYes = true;
    for (let j = 0; j < input[i].length; j++) {
      if (input[i][j] === "(") {
        count = count + 1;
      } else {
        count = count - 1;
        if (count < 0) {
          isYes = false;
          break;
        }
      }
    }

    if (isYes && count === 0) {
      results.push("YES");
    } else {
      results.push("NO");
    }
  }
  return results;
}

console.log(solution(input).join("\n"));

스택말고 단순 갯수 세서 구하는 방법도 있다.