标签:space pop logs function min 括号 cti sim 需要
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.
对含有+ - * /的运算符,因为* /的优先级高于+ -,碰到了* /,前一个运算符若是+ 或者-,它需要延迟计算,因此对所有都要用到栈。
public class Solution { public int calculate(String s) { Stack<Integer> nums = new Stack<Integer>(); Stack<Character> ops = new Stack<Character>(); int re = 0, num = 0; char op = ‘+‘; for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case ‘+‘: case ‘-‘: if (op == ‘+‘) { re = re + num; } else { re = re - num; } num = 0; op = s.charAt(i); break; case ‘(‘: nums.push(re); ops.push(op); re = 0; op = ‘+‘; break; case ‘)‘: if (op == ‘+‘) { re = re + num; } else { re = re - num; } num = 0; char c = ops.pop(); int prev = nums.pop(); if (c == ‘+‘) { re = prev + re; } else { re = prev - re; } break; case ‘ ‘: break; default: num = 10 * num + s.charAt(i) - ‘0‘; } } if (num != 0) { if (op == ‘+‘) { return re + num; } else { return re - num; } } return re; } }
标签:space pop logs function min 括号 cti sim 需要
原文地址:http://www.cnblogs.com/yuchenkit/p/7169496.html