[알고리즘] 백준 9012 괄호 (JS)

Daon·2023년 3월 27일
0

알고리즘

목록 보기
7/11
post-thumbnail

되게 유명한 문제인듯하다
인형뽑기 이런것도 그렇고
이렇게 짝이 맞는문제를 해결 할 때 Stack을 사용하여 해결하였다.

요구사항

1.'(', ')' VPS인 경우 'YES' 아닌경우 'NO'

내풀이

function solution(n, VPS) {
  let str = "";
  for (let i = 0; i < n; i++) {
    const arr = [];
    str = VPS[i];
    console.log(` i :${str}`);
    arr.push(str[0]);
    for (let j = 1; j < str.length; j++) {
      if (arr.length == 0 || arr[arr.length - 1] === str[j]) {
        arr.push(str[j]);
      } else {
        console.log(`pop :${arr.pop()}`);
      }
    }
    console.log(arr);
    console.log(arr.length ? "NO" : "YES");
  }
}

const VPS = [
  "(())())",
  "(((()())()",
  "(()())((()))",
  "((()()(()))(((())))()",
  "()()()()(()()())()",
  "(()((())()(",
];
solution(6, VPS);

stack을 class로 구현해서 할까 했지만 사실 구현해봤자 그 안에서 객체나 배열로 하기 때문에
그냥 arr 배열로 문제를 해결하였다

profile
같이 일하고싶은 그런 개발자!

0개의 댓글