问题:
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.
解决:
① 使用栈 + 后缀表达式。 把sign直接用int存在stack里面,'+'就存成1, '-'存成-1。 使用一个栈来辅助计算,用个变量sign来表示当前的符号,我们遍历给定的字符串s,如果遇到了数字,由于可能是个多位数,所以我们要用while循环把之后的数字都读进来,然后用sign*num来更新结果res;如果遇到了加号,则sign赋为1,如果遇到了符号,则赋为-1;如果遇到了左括号,则把当前结果res和符号sign压入栈,res重置为0,sign重置为1;如果遇到了右括号,结果res乘以栈顶的符号,栈顶元素出栈,结果res加上栈顶的数字,栈顶元素出栈。
class Solution {//14ms
public int calculate(String s) {
int res = 0;
int num = 0;
int sign = 1;
int len = s.length();
Stack<Integer> stack = new Stack<>();
for (int i = 0;i < len;i ++){
char c = s.charAt(i);
if (c >= '0' && c <= '9'){
num = num * 10 + (c - '0');
}else if (c == '+' || c == '-'){
res += sign * num;
num = 0;
sign = (c == '+') ? 1 : -1;
}else if (c == '('){
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
}else if (c == ')'){
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
}
res += sign * num;
return res;
}
}
② 递归方法。
public class Solution {//7ms
int i = 0;//因为使用递归计算()内的内容,所以放在外面,否则会栈溢出异常
public int calculate(String s) {
int num1 = 0;
int num2 = 0;
char op = '+';
while (i < s.length()){
char c = s.charAt(i ++);
if (c == '+' || c == '-'){
num1 = compute(num1,num2,op);
op = c;
num2 = 0;
}else if (c >= '0' && c <= '9'){
num2 = num2 * 10 + c - '0';
}else if (c == '('){
num2 = calculate(s);
}else if (c == ')'){
break;
}
}
return compute(num1,num2,op);
}
public int compute(int num1,int num2,char op){
if (op == '+'){
return num1 + num2;
}
if (op == '-'){
return num1 - num2;
}
return 0;
}
}
③ 递归方法。我们用一个变量count,遇到左括号自增1,遇到右括号自减1,当count为0的时候,说明括号正好完全匹配,这个trick在验证括号是否valid的时候经常使用到。然后我们就是根据左右括号的位置提取出中间的子字符串调用递归函数,返回值赋给num。
class Solution {//120ms
public static int calculate(String s) {
int res = 0;
int num = 0;
int sign = 1;
int len = s.length();
for (int i = 0;i < len;i ++){
char c = s.charAt(i);
if (c >= '0' && c <= '9'){
num = num * 10 + (c - '0');
}else if (c == '('){
int j = i;
int count = 0;
for (;i < len;i ++){
if (s.charAt(i) == '(') count ++;
if (s.charAt(i) == ')') count --;
if (count == 0) break;
}
num = calculate(s.substring(j + 1,i));
}
if (c == '+' || c == '-' || i == len - 1){
res += sign * num;
num = 0;
sign = (c == '+')? 1 : -1;
}
}
return res;
}
}