괄호문자제거

WooBuntu·2021년 2월 23일
0

JS 90제

목록 보기
21/33
  • 내 풀이
const solution = string => {
  let standard = 0;
  let answer = '';
  for (const char of string) {
    if (char == '(') {
      standard++;
      continue;
    } else if (char == ')') {
      standard--;
      continue;
    }
    if (standard == 0) answer += char;
  }
  return answer;
};

const result = solution('(A(BC)D)EF(G(H)(IJ)K)LM(N)');
console.log(result);
  • 스택을 이용한 풀이
const solution = s => {
  let answer;
  let stack = [];
  for (let x of s) {
    if (x === ')') {
      while (stack.pop() !== '(');
    } else stack.push(x);
  }
  answer = stack.join('');
  return answer;
};

const result = solution('(A(BC)D)EF(G(H)(IJ)K)LM(N)');
console.log(result);

0개의 댓글