標籤:
Basic Calculator
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
https://leetcode.com/problems/basic-calculator/
這這這不是我每天都為之糾結的尾碼運算式嗎。
題目比較簡單只有加減法,而且沒有算上負數。
我賭5毛,將來會有一道hard就是這題帶上負數,小數,大小括弧,乘除法之類,名字我都起好了Basic Calculator II。
2個棧,第一個是放運算結果(或者中間運算結果)的棧resultStack,第二個是放運算子的棧opStack。
舉栗子:1+2
1 --> resultStack : [1], opStack : []
+ --> resultStack : [1], opStack : [+]
2 --> resultStack : [1,2], opStack : [+]
壓縮二元運算操作compress_2operators() --> resultStack : [3], opStack : []
結束
舉栗子2: 3-(2-1)
3 --> resultStack : [3], opStack : []
- --> resultStack : [3], opStack : [-]
( --> resultStack : [3], opStack : [-,(]
2 --> resultStack : [3,2], opStack : [-,(]
- --> resultStack : [3,2], opStack : [-,(,-]
1 --> resultStack : [3,2,1], opStack : [-,(,-]
) --> 壓縮括弧操作compress_bracket(),中間會調用compress_2operators() --> resultStack : [3,1], opStack : [-]
壓縮二元運算操作compress_2operators() --> resultStack : [2], opStack : []
結束
如果要加上乘除法,需要修改一下正則,加上乘除法和加減法的優先順序。
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var calculate = function(s) { 6 var resultStack = []; 7 var opStack = []; 8 var temp = ""; 9 for(var i = 0; i < s.length; i++){10 var ch = s[i];11 if(/^(\+|\-)$/.test(ch)){ // + -12 compress_2operators();13 opStack.push(ch);14 } else if (ch === ‘(‘){15 opStack.push(ch);16 } else if (ch === ‘)‘){17 compress_bracket();18 } else if (/^[0-9]$/.test(ch)){19 temp += ch;20 }21 22 if(s[i + 1] && /^(\+|\-|\(|\))$/.test(s[i + 1])){ // + - ( )23 if(temp !== ""){24 resultStack.push(parseInt(temp));25 temp = "";26 }27 }28 }29 if(temp !== ""){30 resultStack.push(parseInt(temp));31 temp = "";32 }33 compress_2operators();34 return resultStack.pop();35 36 function compress_bracket(){37 while(opStack[opStack.length - 1] !== ‘(‘){38 compress_2operators();39 }40 opStack.pop(); //(41 }42 function compress_2operators(){43 while(/^(\+|\-)$/.test(opStack[opStack.length - 1])){ // + -44 var op = opStack.pop();45 var right = resultStack.pop();46 var left = resultStack.pop();47 if(op === ‘+‘){48 resultStack.push(left + right);49 }else{50 resultStack.push(left - right);51 }52 }53 }54 };
[LeetCode][JavaScript]Basic Calculator