[백준 9012] 괄호.js

쿼카쿼카·2022년 8월 15일
0

알고리즘

목록 보기
1/67
post-thumbnail

코드

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');

// const input = [6, '(())())', '(((()())()', '(()())((()))', '((()()(()))(((())))()', '()()()()(()()())()', '(()((())()('];

for(let i=1; i<input.length ; i++) {
  const str = input[i];
  let count = 0;

  for(let j=0; j<str.length; j++) {
    if(str[j] === '(') count++;
    else count--;

    if(count < 0) {
      console.log('NO');
      break;
    }
  }

  count === 0 && console.log('YES');
  count > 0 && console.log('NO');
}

풀이

  • shift나 pop을 사용x(시간 아끼기). for문에서 i=1부터 시작
  • '(' 만나면 count++, ')' 만나면 count--
  • count가 음수가 되면 순서는 개나 줘버린 괄호이므로 바로 'NO' 출력 후 넘어감
  • 괄호를 모두 탐색할 때까지 count가 음수가 아니었다면 for문을 탈출해 판별
    • count === 0 이면 괄호 갯수가 딱 맞아 떨어진다는 뜻이라 'YES'
    • count > 0 이면 왼쪽 괄호 수가 더 많다는 뜻이라 'NO'

다른 방법

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');

// const input = [6, '(())())', '(((()())()', '(()())((()))', '((()()(()))(((())))()', '()()()()(()()())()', '(()((())()('];

const result = [];

for(let i=1; i<input.length ; i++) {
  const str = input[i];
  let count = 0;

  for(let j=0; j<str.length; j++) {
    if(str[j] === '(') count++;
    else count--;

    if(count < 0) {
      result.push('NO');
      break;
    }
  }

  count === 0 && result.push('YES');
  count > 0 && result.push('NO');
}

console.log(result.join('\n'));

for 안에서 console.log 자주 사용하면 안 좋다고 하여 성장하는 마음으로 push로 변경 후 마지막에 console.log 실행


오히려 12ms나 더 많이 나왔다...어쩌라는 거지?
이유를 아는 분들은 댓글 남겨주세요!!
선물로 수학의 정석 수학I 을 드립니다.

profile
쿼카에요

0개의 댓글