[LeetCode] Basic Calculator II

简介: The basic idea of is as follows: Maintain a deque operands for the numbers and another deque operations for the operators +, -, *,/`.

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 };

 

目录
相关文章
|
存储
LeetCode 227. Basic Calculator II
实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
67 0
LeetCode 227. Basic Calculator II
Leetcode [224] Basic Calculator 基于语法树的解法
通过生成语法树,解决表达式求值问题
284 0
LeetCode 227 Basic Calculator II
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51337819 ...
696 0
|
3月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
4月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
63 6
|
4月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
128 2
|
1月前
|
机器学习/深度学习 人工智能 自然语言处理
280页PDF,全方位评估OpenAI o1,Leetcode刷题准确率竟这么高
【10月更文挑战第24天】近年来,OpenAI的o1模型在大型语言模型(LLMs)中脱颖而出,展现出卓越的推理能力和知识整合能力。基于Transformer架构,o1模型采用了链式思维和强化学习等先进技术,显著提升了其在编程竞赛、医学影像报告生成、数学问题解决、自然语言推理和芯片设计等领域的表现。本文将全面评估o1模型的性能及其对AI研究和应用的潜在影响。
46 1
|
3月前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口