Basic Calculator

题目描述:

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));
    }  
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值