괄호 문자 제거(Stack)

설정·2021년 3월 13일
0
  • My Solution 1

  • Answer

  • In Progress
function solution(s) {
  let stack = [];
  let cnt = 0;
  
  for(let i=0; i<s.length; i++) {
    if(s[i] === ')') {
      while(cnt > 0) {
        stack.pop();
        cnt--;
        console.log('pop', cnt, s[i]);
      }
    } else {
      stack.push(s[i]);
      cnt++;
      console.log('push', cnt, s[i]);
    }
  }
  
  return stack;
}

let str="(A(BC)D)EF(G(H)(IJ)K)LM(N)";
console.log(solution(str));
  • output
push 1 (
push 2 A
push 3 (
push 4 B
push 5 C
pop 4 )
pop 3 )
pop 2 )
pop 1 )
pop 0 )
push 1 D
pop 0 )
push 1 E
push 2 F
push 3 (
push 4 G
push 5 (
push 6 H
pop 5 )
pop 4 )
pop 3 )
pop 2 )
pop 1 )
pop 0 )
push 1 (
push 2 I
push 3 J
pop 2 )
pop 1 )
pop 0 )
push 1 K
pop 0 )
push 1 L
push 2 M
push 3 (
push 4 N
pop 3 )
pop 2 )
pop 1 )
pop 0 )

0개의 댓글