[LeetCode] Basic Calculator II

The basic idea of is as follows:

  1. Maintain a deque operands for the numbers and another deque operations for the operators +, -, *,/`.
  2. Scan the expression from left to right, each time we meet a digit, extract the whole number with and after it, push the number into operands.
  3. If we meet * or /, we extract the next number in the expression and the last number inoperands, compute the intermediate result of them and store the result into operands.
  4. If we meet + or -, we store it into operations.
  5. After scanning the whole expression, we visit operations from front to back and perform the operations with the corresponding elements (each time with the first two elements inoperands).

Let‘s see a concrete example and run the above process. Suppose we want calculate 1-2*3+4, we will first push 1 into operands, - into operations and then 2 into operands. Then we meet*, which has higher priority over + and -. We take 2 out from operands and extract the next operand 3 and multiply them, obtaining 6. We push 6 into operands. Then we push + intooperations and 4 into operands.

So, after the scanning of the expression, operands will be [1, 6, 4]operations will be [-, +]. The remaining computation is 1-6+4. We perform it from front to back. Specifically, we take 1and 6 out from operands and - out from operations and perform 1 - 6 = 5 and push 5 into operands.

Now operands is [-5, 4] and operations is [+]. We simply repeat the above process and perform -5+4=-1. We push -1 into operands. Finally, operands is [-1] and operations is empty. Now the remaining single number in operands is the result and we are done.

In a word, my solution breaks down the original expression into additions and subtractions and compute multiplications and divisions first while scanning the expression.

The idea to use deque is that when we perform step 2, we need to know the last element we push to operands, which is like the top of a stack. Moreover, when we perform step 5, we need to know the first element we push to operands, which is like the front of a queue. Due to this double-ended structure (we need to be able to access the last added and first added element), a deque is a natural choice.

The code is as follows.

 1 class Solution {
 2 public:
 3     int calculate(string s) {
 4         deque<int> operands;
 5         deque<char> operations;
 6         for (int i = 0; i < (int)s.length(); i++) {
 7             if (isdigit(s[i])) {
 8                 int num = extract_num(s, i);
 9                 operands.push_back(num);
10             }
11             else if (s[i] == ‘*‘ || s[i] == ‘/‘) {
12                 char op = s[i];
13                 int first = operands.back();
14                 operands.pop_back();
15                 i++;
16                 while (!isdigit(s[i])) i++;
17                 int second = extract_num(s, i);
18                 if (op == ‘*‘)
19                     operands.push_back(first * second);
20                 else operands.push_back(first / second);
21             }
22             else if (s[i] == ‘+‘ || s[i] == ‘-‘)
23                 operations.push_back(s[i]);
24         }
25         while (!operations.empty()) {
26             char op = operations.front();
27             operations.pop_front();
28             int first = operands.front();
29             operands.pop_front();
30             int second = operands.front();
31             operands.pop_front();
32             if (op == ‘+‘)
33                 operands.push_front(first + second);
34             else operands.push_front(first - second);
35         }
36         return operands.front();
37     }
38 private:
39     int extract_num(string& s, int& i) {
40         int num = 0;
41         while (i < (int)s.length() && isdigit(s[i]))
42             num = num * 10 + s[i++] - ‘0‘;
43         i--;
44         return num;
45     }
46 }; 

Of course, there is still much redundancy in the above code. In fact, there is no need to use any deque-like data structure to store all the numbers or operators. We can simply solve it in O(1) space. A nice solution is at this link. I have rewritten it below.

 1 class Solution {
 2 public:
 3     int calculate(string s) {
 4         int i = 0, res = 0, sign = 1;
 5         int num = extract_num(s, i);
 6         while (i < (int)s.length()) {
 7             if (s[i] == ‘+‘ || s[i] == ‘-‘) {
 8                 char op = s[i];
 9                 res += num * sign;
10                 num = extract_num(s, ++i);
11                 sign = (op == ‘+‘ ? 1 : -1);
12             }
13             else if (s[i] == ‘*‘)
14                 num *= extract_num(s, ++i);
15             else if (s[i] == ‘/‘)
16                 num /= extract_num(s, ++i);
17         }
18         res += num * sign;
19         return res;
20     }
21 private:
22     int extract_num(string& s, int &i) {
23         int num = 0;
24         while (i < (int)s.length()) {
25             if (isdigit(s[i])) num = num * 10 + s[i] - ‘0‘;
26             else if (s[i] != ‘ ‘) return num;
27             i++;
28         }
29         return num;
30     }
31 };
时间: 2024-12-21 08:52:04

[LeetCode] Basic Calculator II的相关文章

LeetCode——Basic Calculator II

Description: 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. You may assume that

[LeetCode] 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. You may assume that the given ex

LeetCode 227. 基本计算器 II(Basic Calculator II)

227. 基本计算器 II 227. Basic Calculator II 题目描述 实现一个基本的计算器来计算一个简单的字符串表达式的值. 字符串表达式仅包含非负整数,+,-,*,/ 四种运算符和空格.整数除法仅保留整数部分. LeetCode227. Basic Calculator II中等 示例?1: 输入: "3+2*2" 输出: 7 示例 2: 输入: " 3/2 " 输出: 1 示例 3: 输入: " 3+5 / 2 " 输出:

LeetCode OJ Basic Calculator II

Basic Calculator II 题目 思路 和这个一样:Basic Calculator I 代码 class ExpressionTransformation { public: string trans_to_postfix_expression_to_s(string); // 将得到的表达式转化为后缀表达式 long long int calculate_from_postfix_expression(); // 根据后缀表达式计算值 private: vector<string

【LeetCode】227. Basic Calculator II

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. You may assu

【Leetcode】Basic Calculator II

题目链接:https://leetcode.com/problems/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 s

Leetcode 227. Basic Calculator II JAVA语言

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. You may assume that the given ex

[LeetCode#227] Basic Calculator II

Problem: 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. You may assume that the

Java for LeetCode 227 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. You may assume that the given ex