fffo

[js문제풀이]괄호 계산 본문

Programming/Algorithm

[js문제풀이]괄호 계산

gggs 2021. 10. 16. 15:57

문제

접근 및 풀이

괄호 안의 누적되는 수를 어떻게 처리할지 고민이 된 문제였다. 괄호를 축적하는 스택에 계산된 수를 넣고 pop했을 때 숫자인지 괄호인지 분기를 만드는 식으로 접근했다. 중복되는 코드가 많아서 함수로 따로 뺐는데 가독성이 오히려 떨어진 것 같다. 

코드

function answer(str) {
  let result = 0;
  const stack = [];
  for (let i in str) {
    if (str[i] === '(' || str[i] === '[') {
      stack.push(str[i]);
    } else if (str[i] === ')') {
      if (f('(', 2, stack)) return 0;
    } else if (str[i] === ']') {
      if (f('[', 3, stack)) return 0;
    }
  }
  return stack.reduce((acc,cur)=> acc+cur);
}
function f(openChar, weight, stack) {
  let poped = stack.pop();
  let num = 0;
  while (poped !== openChar) {
    if (typeof poped !== 'number') return true;
    num += poped;
    poped = stack.pop();
  }
  stack.push(num ? num * weight : weight);
}

출처

제로베이스  네카라쿠배 온라인 프론트엔드 1기 연습문제

'Programming > Algorithm' 카테고리의 다른 글

[js문제풀이] 거스름 돈  (0) 2021.10.17
[js문제풀이] 가장 먼 노드  (0) 2021.10.16
[js문제풀이]여행경로  (0) 2021.10.15
[js문제풀이]2 x n 타일  (0) 2021.10.15
[js문제풀이] 디스크 컨트롤러  (0) 2021.10.13
Comments