[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
实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
40 0
LeetCode 227. Basic Calculator II
Leetcode [224] Basic Calculator 基于语法树的解法
通过生成语法树,解决表达式求值问题
250 0
LeetCode 227 Basic Calculator II
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51337819 ...
666 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38

热门文章

最新文章