[백준] 10799 | 쇠막대기 | 자바스크립트

문제

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

 

정답 코드

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

const input = fs.readFileSync(filePath).toString().trim();

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

  // 레이저인지 막대기의 끝인지 구분하기 위한 변수
  let prev = "";

  for (let i = 0; i < input.length; i++) {
    // 괄호
    const parentheses = input[i];

    if (parentheses === "(") {
      stack.push(parentheses);
    } else {
      stack.pop();

      // 만약 이전 괄호가 ) 이면 막대기의 마지막
      if (prev === ")") {
        result = result + 1;
      } else {
        result = result + stack.length;
      }
    }

    prev = parentheses;
  }

  return result;
}

console.log(solution(input));
  • "(" 가 나오면 스택에 추가
  • ")" 가 나오면 스택에서 제거, 이전 문자가 "(" 이면 레이저 ")" 이면 막대기의 끝을 의미
    • 이전 문자가 "(" 이면 레이저를 의미하므로 스택에 있는 개수만큼 조각 수 증가
    • 이전 문자가 ")" 이면 막대기의 끝을 의미하므로 막대기 하나가 종료되므로 조각 수 1개 증가