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.
Subscribe to see which companies asked this question
Stack 存起来就行
public class Solution {
private int calc(Stack<String> stack2){
int ret = 0;
int state = 1;//1为加0为减
while(!stack2.empty()){
int num = 0;
String tem = stack2.pop();
if(tem.equals(")"))break;
else if(tem.equals("("))num=calc(stack2);
else if(tem.equals("+")){state=1;
continue;
}
else if(tem.equals("-")){state=0;
continue;
}else {
num=Integer.parseInt(tem);
}
if(state==1){
ret=ret+num;
}else{
ret=ret-num;
}
}
return ret;
}
public int calculate(String s) {
Stack<String> stack=new Stack<>();
Stack<String> stack2 = new Stack<>();
int length = s.length();
for(int i=length-1;i>=0;){
char k = s.charAt(i);
if(k==' '){
i--;
continue;
}
if(k==')'||k=='('||k=='+'||k=='-'){
String t = ""+s.charAt(i);
i--;
stack2.push(t);
continue;
}
String t = "";
while(i>=0&&(s.charAt(i)==' '||('0'<=s.charAt(i)&&'9'>=s.charAt(i)))){
k=s.charAt(i);
if(k==' '){
i--;
continue;
}
t = k+t;
i--;
}
stack2.push(t);
}
return calc(stack2);
}
}