seunghyun Note

[백준] 4949번 : 균형잡힌 세상(스택 공부 부수기) with JS 본문

코딩테스트/프로그래머스

[백준] 4949번 : 균형잡힌 세상(스택 공부 부수기) with JS

승숭슝현 2024. 1. 18. 16:05

 

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

 

4949번: 균형잡힌 세상

각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에

www.acmicpc.net

문제 풀이

괄호가 한 개가 아닌 여러 개일 때 신경 쓸 것이 많다. 

vps function에서 조건을 여러가지 걸고 아닐 경우 바로 false로 return 하기

main에서는 vps function이 true일 경우와 문자열의 마지막이 '.'일 경우 yes로 리턴해준다.

const fs = require("fs");

//const input = require("fs").readFileSync("/dev/stdin").toString().trim().split("\n");
const input = fs.readFileSync("예제.txt").toString().trim().split("\n");
let ans = [];
let i = 0;
while (input[i] !== ".") {
  ans.push(
    vps(input[i]) && input[i].charAt(input[i].length - 1) === "." ? "yes" : "no"
  );
  i++;
}

console.log(ans.join("\n"));

function vps(str) {
  let stack = [];
  for (let value of str) {
    if (value === "[" || value === "(") stack.push(value);
    else if (value === "]")
      if (stack[stack.length - 1] === "[") {
        stack.pop();
      } else return false;
    else if (value === ")")
      if (stack[stack.length - 1] === "(") {
        stack.pop();
      } else return false;
  }
  return stack.length === 0;
}

 

 

728x90