您的位置:首页 > 其它

[leetcode] Basic Calculator 使用堆栈计算表达式的值

2018-02-24 09:51 330 查看
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.

解题思路:

因为只存在加减法,只需要考虑表达式前的符号,全部使用加法完成计算即可;

遇到左括号,就把已经计算出的部分表达式结果值压栈,并把当前括号前的符号压栈,继续计算括号里的表达式;

遇到右括号,先把括号里的计算结果乘上栈顶保存着的括号的符号,弹出栈顶符号,再加上当前栈顶保存的上一部分的结果,组成总结果。

class Solution {
public int calculate(String s) {

int res = 0, sign = 1;

String expression = s.replaceAll(" ","");

int len = expression.length();

Stack<Integer> stk = new Stack<>();

for(int i=0;i<len;++i){

char c = expression.charAt(i);

if(c >= '0' && c <= '9'){
int sum = 0;
while(c >='0' && c <='9'){
sum = sum * 10 + (c - '0');
if(++i < len){
c = expression.charAt(i);
}else{
break;
}
}
res = res + sum * sign;
i--;
}else if(c == '+'){
sign = 1;
}else if(c == '-'){
sign = -1;
}else if(c == '('){
stk.push(res);
stk.push(sign);
res = 0;
sign = 1;
}else if(c == ')'){
res *= stk.pop();
res += stk.pop();
}

}

return res;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐