從 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

更新於: 22-Apr-2021

257 次瀏覽

啟動你的 職業生涯

完成課程即可獲得認證

開始
廣告