문제
첫 번째이자 유일한 인수로 일련의 수학 표현식 str을 취하는 JavaScript 함수를 작성해야 합니다.
우리 함수의 임무는 연산과 피연산자를 제자리에 유지하는 표현식에서 괄호를 제거하는 것입니다.
예를 들어, 함수에 대한 입력이 -
인 경우입력
const str = 'u-(v-w-(x+y))-z';
출력
const output = 'u-v+w+x+y-z';
예시
다음은 코드입니다 -
const str = 'u-(v-w-(x+y))-z';
const removeParentheses = (str = '') => {
let stack = []
let lastSign = '+'
for (let char of str) {
if (char === '(' || char === ')') {
lastSign = stack[stack.length - 1] || '+'
} else if (char === '+') {
if (stack[stack.length - 1] !== '-' && stack[stack.length - 1] !== '+') {
stack.push(lastSign)
}
} else if (char === '-') {
if (lastSign === '-') {
if (stack[stack.length - 1] === '-') stack.pop()
stack.push('+')
} else {
if (stack[stack.length - 1] === '+') stack.pop()
stack.push('-')
}
} else {
stack.push(char)
}
}
return stack.join('').replace(/^\+/, '')
};
console.log(removeParentheses(str)); 출력
u-v+w+x+y-z