首页 > 编程语言 > 详细

Java for LeetCode 224 Basic Calculator

时间:2015-06-15 22:00:13      阅读:412      评论:0      收藏:0      [点我收藏+]

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即可,JAVA实现如下:

    public int calculate(String s) {
		Stack<Integer> sign = new Stack<Integer>();
		sign.push(1);
		int lastOp = 1;
		int res = 0;
		for (int i = 0; i < s.length(); i++) {
			switch (s.charAt(i)) {
			case ‘ ‘:
				break;
			case ‘+‘:
				lastOp = 1;
				break;
			case ‘-‘:
				lastOp = -1;
				break;
			case ‘(‘:
				sign.push(lastOp*sign.peek());
				lastOp=1;
				break;
			case ‘)‘:
				sign.pop();
				break;
			default:
				int num = 0;
				while (i < s.length() && Character.isDigit(s.charAt(i)))
					num = num * 10 + s.charAt(i++) - ‘0‘;
				i--;
				res += lastOp * num * sign.peek();
			}
		}
		return res;
    }

 

Java for LeetCode 224 Basic Calculator

原文:http://www.cnblogs.com/tonyluis/p/4579092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!