首页 > 其他 > 详细

[LeetCode] 224. Basic Calculator

时间:2020-05-17 09:16:53      阅读:46      评论:0      收藏:0      [点我收藏+]

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: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

  • You may assume that the given expression is always valid.
  • Do not use the 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 题目总结

[LeetCode] 224. Basic Calculator

原文:https://www.cnblogs.com/cnoodle/p/12903414.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!