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 .
Example 1:
Input: "1 + 1" Output: 2Example 2:
Input: " 2-1 + 2 " Output: 3Example 3:
Input: "(1+(4+5+2)-3)+(6+8)" Output: 23
Note:
eval
built-in library function.基本计算器。题意是实现一个基本的计算器来计算一个简单的字符串表达式的值。注意这个题是不需要处理乘法和除法的。
思路是用stack。按字符逐个遍历input,因为没有无效的case所以不需要处理一些奇奇怪怪的比如是不是字母的case。一开始遍历的时候设置一个变量res和一个变量sign记录最后的结果和结果的正负号。计算数字的时候记得看数字是不是有多个digit。
最后着重讲一下带括号的部分,如果你遇到一个左括号,就需要把之前的res和sign加入stack(这里顺序不能错,先加res再加sign),并且把res和sign都重新设置成0和1,使得他们可以记录括号内的部分的结果和正负情况。当遇到右括号的时候则开始结算括号内的结果。此时的res是记录了括号内的res,stack.pop()会先弹出sign;再弹一次的时候就得到了括号部分之前的res,再相加就得到最终的结果了。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int calculate(String s) { 3 Stack<Integer> stack = new Stack<>(); 4 int sign = 1; 5 int res = 0; 6 for (int i = 0; i < s.length(); i++) { 7 if (Character.isDigit(s.charAt(i))) { 8 int num = s.charAt(i) - ‘0‘; 9 while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { 10 num = num * 10 + s.charAt(i + 1) - ‘0‘; 11 i++; 12 } 13 res += num * sign; 14 } else if (s.charAt(i) == ‘+‘) { 15 sign = 1; 16 } else if (s.charAt(i) == ‘-‘) { 17 sign = -1; 18 } else if (s.charAt(i) == ‘(‘) { 19 stack.push(res); 20 stack.push(sign); 21 res = 0; 22 sign = 1; 23 } else if (s.charAt(i) == ‘)‘) { 24 res = res * stack.pop() + stack.pop(); 25 } 26 } 27 return res; 28 } 29 }
[LeetCode] 224. Basic Calculator
原文:https://www.cnblogs.com/cnoodle/p/12903414.html