题目描述:
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这里的用栈来做,当计算的时候要用另外一个栈来过渡。
代码如下:
public class Solution {
//这个stack中没有"(",")"," ",只有"+","-"和整数
public String calculateSimple(Stack<String> stack){
while(stack.size()>1){
int n2=Integer.parseInt(stack.pop());
String ch=stack.pop();
int n1=Integer.parseInt(stack.pop());
if(ch.equals("+"))
stack.push(n2+n1+"");
if(ch.equals("-"))
stack.push(n2-n1+"");
}
return stack.pop();
}
public int calculate(String s) {
Stack<String> stack=new Stack<String>();
Stack<String> newStack=new Stack<String>();
for(int i=0;i<s.length();i++){
//当碰到')'直接将()中的数计算出来
if(s.charAt(i)==')'){
String popStr="";
while(!(popStr=stack.pop()).equals("("))
newStack.push(popStr);
stack.push(calculateSimple(newStack));
}
//当碰到整数的时候看前面的是否有整数,如果有整数就将两者一起放到栈中
if(s.charAt(i)<='9'&&s.charAt(i)>='0'){
if(!stack.isEmpty()){
String str=stack.peek();
if(str.equals("+")||str.equals("-")||str.equals("(")){
stack.push(s.charAt(i)+"");
}else{
int n=Integer.parseInt(stack.pop())*10+s.charAt(i)-'0';
stack.push(n+"");
}
}else{
stack.push(s.charAt(i)+"");
}
}
if(s.charAt(i)=='+'||s.charAt(i)=='-'||s.charAt(i)=='('){
stack.push(s.charAt(i)+"");
}
}
while(!stack.isEmpty())
newStack.push(stack.pop());
return Integer.parseInt(calculateSimple(newStack));
}
}