标签:
Basic Calculator II
问题:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
思路:
栈的应用,一个栈存放操作数,一个栈存放运算符
我的代码:
public class Solution { private Stack<Character> opers = new Stack<Character>(); private Stack<Integer> values = new Stack<Integer>(); public int calculate(String s) { if(s== null || s.length()==0) return 0; char[] tokens = s.toCharArray(); for(int i=0; i<tokens.length; i++) { char c = tokens[i]; if(c == ‘ ‘) continue; else if(c<=‘9‘ && c>=‘0‘) { int result = 0; while(i<tokens.length && tokens[i] >=‘0‘ && tokens[i] <=‘9‘) { result = result*10 + (tokens[i]-‘0‘); i++; } values.push(result); i--; } else if(c == ‘(‘) opers.push(c); else if(c == ‘)‘) { if(!opers.isEmpty() && opers.peek() != ‘(‘) values.push(applyOp(opers.pop(), values.pop(), values.pop())); opers.pop(); } else { while(!opers.isEmpty() && hasPrecedence(c, opers.peek())) { values.push(applyOp(opers.pop(), values.pop(), values.pop())); } opers.add(c); } } while (!opers.empty()) { values.push(applyOp(opers.pop(), values.pop(), values.pop())); } return values.pop(); } public static boolean hasPrecedence(char op1, char op2) { return op2 == ‘(‘ ? false : true; } public static int applyOp(char op, int b, int a) { switch (op) { case ‘+‘: return a + b; case ‘-‘: return a - b; } return 0; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4596937.html