Remove Parentheses Letter (Stack)

Problem

Write a program that removes all characters between parentheses ( ) in the input string and prints only the remaining characters.

input

  • A string of parentheses is entered on the first line
  • The length of the string does not exceed 100.
(A(BC)D)EF(G(H)(IJ)K)LM(N)

output

Only the remaining characters are printed.

EFLM

Solution

use lastIndexOf()

function solution(s) {
	let answer = '';

	for (let x of s) {
		answer += x;
		if (x === ')') {
			const pairIndex = answer.lastIndexOf('(');
			answer = answer.slice(0, pairIndex);
		}
	}

	return answer;
}

use while loop

function solution(s) {
	let answer,
		stack = [];

	for (let x of s) {
		if (x === ')') {
			while (stack.pop() !== '(');
		} else stack.push(x);
	}

	answer = stack.join('');

	return answer;
}