Basic Calculator



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. 

关键点:stack

思路:遍历字符串,将字符串中的字符分成四类:

1) 数字0~9:采用类似字符串转整数的方法,得到操作数(operand = 10 * operand + c - '0')

2) 操作码“+”,“-”:操作数获取完成,此时可进行相应计算,并开始新一轮的计算

3) "(":标志着子字符串的开始,需要将父字符串的状态保存,即用stack保存之前的计算结果以及操作码

4) ")":标志着子字符串的结束,可将子字符串的结果加回父字符串。


代码:

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0)
			return 0;
        int result = 0, opr = 0;
        int length = s.length();
        Stack<Integer> stack = new Stack<>();
        Map<Character, Integer> map = new HashMap<>();
        map.put('+', 1);
        map.put('-', -1);
        // initial operator is '+'
        char operator = '+';
        for(int i = 0; i < length; i++) {
        	char c = s.charAt(i);
        	if(c == '(') {
        		stack.push(result);
        		stack.push(map.get(operator));
        		opr = 0;
        		result = 0;
        		operator = '+';
        	}
        	if(c == ')') {
        		result += map.get(operator)* opr;
        		// a is operator
        		int a = stack.pop();
        		// b is operand
        		int b = stack.pop();
        		result = b + a * result;
        		opr = 0;
        	}
        	if(c >= '0' && c <= '9') {
        		opr = 10 * opr + c - '0';
        	}
        	if(c == '+' || c == '-') {
        		result += map.get(operator) * opr;
        		operator = c;
        		opr = 0;
        	}
        }
        result += map.get(operator) * opr;
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值