题目描述:
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
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
题目分析:
这道题是标准算数表达式的一个变式,区别在于题目之中的有括号有省略的情况。所以整体思路为:双栈,一个栈stack放操作数,一个栈opr放操作符。
思路:遇到+ 、-、(的时候,操作符压栈opr
遇到)的时候,从stack 和opr中弹出计算需要的操作数个数,同时把结果压栈stack,直到遇到(为止
在计算完这一组括号了之后,持续计算,到上一个(为止,这是处理()中的数作为一个操作数的情况
遇到数字的情况,压栈,同时计算到(为止,这是保证从左到右的运算数据
注: 也可以以后缀表达的角度来理解这道题。
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
var string = [];
for(var i=0; i<s.length; i++){
if(s[i] == ' ') continue;
var str = "";
while(s[i]-'0'>=0 && s[i] -'9'<=0){
str += s[i];
i++;
}
if(str.length > 0) string.push(str);
s[i] && string.push(s[i]);
}
var stack = [],opr = [],i=0,len=string.length;
while(i<len){
if(string[i] =='+'|| string[i]== '-' || string[i] == '('){
opr.push(string[i]);
i++;
}else if(string[i] == ')'){
while(opr[opr.length-1] !== '('){
var n2 = stack.pop(),
n1 = stack.pop(),
op = opr.pop();
stack.push(op == '+'? n1+n2: n1-n2);
}
opr.pop(); // 去掉(
while(opr.length>0 && opr[opr.length-1]!== '('){//把前面的运算式都计算了
var n2 = stack.pop(),
n1 = stack.pop(),
op = opr.pop();
stack.push(op == '+'? n1+n2: n1-n2);
}
i++;
}else{
stack.push(parseInt(string[i],10));
while(opr.length>0 && opr[opr.length-1]!== '('){//把前面的运算式都计算了
var n2 = stack.pop(),
n1 = stack.pop(),
op = opr.pop();
stack.push(op == '+'? n1+n2: n1-n2);
}
i++;
}
}
return stack.pop();
};