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
因为只有加减法 我们只要考虑括号的问题, 如果括号前面是+号, 括号内运算并不改变, 之间做加减法并入结果中, 如果括号前面是-号, 那么括号内加法, 结果就要减去相应的数. 所以我们用sign来记录数字前面的加减号, stack内部存括号外面的加减号, 这样每次运算只需要num*sign*stack.peek()
用stack和一个sign来记录符号,遇到加号 sign为1, 遇到减号sign 为-1, 遇到左括号 计算当前的符号(sign* stack.peek()) 压入栈内, 遇到右括号 出栈, 遇到数字把数字* sign* stack.peek()加入结果中
public class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<Integer>(); stack.push(1);// 先压入一个1进栈,可以理解为有个大括号在最外面 s = s.replace(" ", ""); int sign = 1, res = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '+') { sign = 1; } else if (c == '-') { sign = -1; } else if (c == '(') { stack.push(sign * stack.peek()); sign = 1; } else if (c == ')') { stack.pop(); } else { int num = 0; while (i < s.length() && Character.isDigit(s.charAt(i))) { num = num * 10 + s.charAt(i) - '0'; i++; } res += num * sign * stack.peek(); i--; } } return res; } }
没有评论:
发表评论