본문 바로가기
개발 노트/백준, 프로그래머스 풀이

[백준 4949/javascript] 균형잡힌 세상

by tokkiC 2022. 10. 23.

스택을 이용해서 푸는 흔한 괄호 문제

다른점이라면 문장에서 괄호만 필터로 꺼내 담아 체크한다는 점뿐이다

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

 

4949번: 균형잡힌 세상

하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 각 줄은 마침표(".")로 끝난다

www.acmicpc.net

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", (line) => {
  if (line === ".") {
    rl.close();
  }
}).on("close", () => {
  solution(line);
  process.exit();
});

const solution = (line) => {
  const arr = line
    .split("")
    .filter((el) => el === "(" || el === ")" || el === "[" || el === "]");

  const chk = [];

  if (arr.length % 2 !== 0) {
    console.log("no");
    return;
  }

  for (let i = 0; i < arr.length; i++) {
    const cur = arr[i];
    if (cur === "[") {
      chk.push(cur);
    }
    if (cur === "]") {
      if (chk[chk.length - 1] === "[") {
        chk.pop();
      } else {
        chk.push(cur);
      }
    }
    if (cur === "(") {
      chk.push(cur);
    }
    if (cur === ")") {
      if (chk[chk.length - 1] === "(") {
        chk.pop();
      } else {
        chk.push(cur);
      }
    }
  }

  if (!chk.length && !chk.length) {
    console.log("yes");
  } else {
    console.log("no");
  }
};

댓글