从 JavaScript 数学表达式中移除括号
问题
我们需要编写一个 JavaScript 函数,它接收一个字符串形式的数学表达式 str,作为第一个也是唯一一个参数。
我们的函数任务是从表达式中移除括号,保留运算符和运算数。
例如,如果输入函数为 −
输入
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP