问题描述
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. 
程序
第一种是普通的方法:先将表达式转成后缀表达式,然后再计算。(TLE)
第二种是简化的方法,比较巧妙。
public class BasicCalculator {
	public int calculate(String s) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		
		// preprocess
		s = s.trim();
		char[] cc = s.toCharArray();
		String new_s = "";
		for (int i = 0; i < cc.length; i++) {
			if (cc[i] == ‘(‘ || cc[i] == ‘)‘) {
				continue;
			}
			if (cc[i] == ‘+‘ || cc[i] == ‘-‘) {
				new_s += " " + cc[i] + " ";
			} else {
				new_s += cc[i];
			}
		}
		String[] items = new_s.split(" ");
		List<String> postExpressionList = new ArrayList<String>();
		Stack<String> st = new Stack<String>();
		// transform to postfix expression
		for (int i = 0; i < items.length; i++) {
			String item = items[i].trim();
			if (item.length() == 0) {
				continue;
			}
			if (item.equals("+") || item.equals("-")) {
				if (!st.isEmpty()) {
					postExpressionList.add(st.pop());
				}
				st.push(item);
			} else {
				postExpressionList.add(item);
			}
		}
		while (!st.isEmpty()) {
			postExpressionList.add(st.pop());
		}
		
		// calculate
		Stack<Integer> calStack = new Stack<Integer>();
		for (String ex : postExpressionList) {
			if (ex.equals("+")) {
				int n1 = calStack.pop();
				int n2 = calStack.pop();
				calStack.push(n1 + n2);
			} else if (ex.equals("-")) {
				int n1 = calStack.pop();
				int n2 = calStack.pop();
				calStack.push(n2 - n1);
			} else {
				calStack.push(Integer.valueOf(ex));
			}
		}
		return calStack.peek();
	}
	
	public int calculate2(String s) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		
		s = s.trim();
		int res = 0, sign = 1;
		Stack<Integer> st= new Stack<Integer>();
		
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (Character.isDigit(c)) {
				int cur = c - ‘0‘;
				while (i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {
					cur = cur * 10 + (s.charAt(i+1) - ‘0‘);
					++i;
				}
				res += sign * cur;
			}else if (c == ‘+‘) {
				sign = 1;
			}else if (c == ‘-‘){
				sign = -1;
			}else if (c == ‘(‘) {
				st.push(res);
				res = 0;
				st.push(sign);
				sign = 1;
			}else if (c == ‘)‘) {
				res = st.pop()*res + st.pop();
				sign = 1;
			}
		}
		
		return res;
	}
}
原文:http://www.cnblogs.com/harrygogo/p/4647978.html