码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 224 Basic Calculator

时间:2015-06-15 22:02:12      阅读:292      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!