[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
the plus
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
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;
}
}
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
evalbuilt-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;
}
}
相关文章推荐
- 使用堆栈将缺少左括号的表达式补全并计算其值
- 使用堆栈计算后缀表达式--java实现
- 使用堆栈结构进行字符串表达式("7*2-5*3-3+6/3")的计算
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- “由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。”
- 使用正则表达式计算字符串中中文字符的个数
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 使用栈的表达式计算程序_main.c
- C#由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 使用ExpressionBuilder 类 在分析页的过程中计算表达式
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 错误:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。
- 异常:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 计算表达式 --堆栈
- 异常:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- Stack-c#堆栈计算表达式
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 使用栈的表达式计算程序.arith_expr.c