[알고리즘] 백준 4949번 균형잡힌 세상(JS)

Daon·2023년 3월 27일
0

알고리즘

목록 보기
8/11
post-thumbnail

전에 글에 올렸던 괄호와 거의 똑같은 문제이다.
다른것은 대괄호가 생겼단것과 문자열 사이에 있다는것이다.


요구사항

1.괄호가 서로 짝이맞는것은 YES 아닌것은 NO

내풀이

function solution(texts) {
  for (let i = 0; i < texts.length; i++) {
    let arr = [];
    let reg = /[a-zA-Z.\s]/g;
    data = texts[i].replace(reg, "");
    data && arr.push(data[0]);

    for (let j = 1; j < data.length; j++) {
      if (arr) data;
      let prev = arr[arr.length - 1];
      if (prev === "(" && data[j] === ")") {
        arr.pop();
      } else if (prev === "[" && data[j] === "]") {
        arr.pop();
      } else {
        arr.push(data[j]);
      }
    }
    console.log(arr.length ? "no" : "yes");
  }
}

const texts = [
  "So when I die (the [first] I will see in (heaven) is a score list).",
  "[ first in ] ( first out ).",
  "Half Moon tonight (At least it is better than no Moon at all].",
  "A rope may form )( a trail in a maze.",
  "Help( I[m being held prisoner in a fortune cookie factory)].",
  "([ (([( [ ] ) ( ) (( ))] )) ]).",
  " .",
];
solution(texts);

나는 풀 때 정규식을 사용해서 문자들을 걷어냈는데 다른 답을보니
그냥 '(', ')', '[', ']' 인경우만 잡아주면 그냥 for문으로 다 돌아보는게 더 좋은 것 같다.

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

0개의 댓글