[字符串高频题]leetcode 227 Basic calculator II

Leetcode 227 Basic calculator II

https://leetcode.com/problems/basic-calculator-ii/description/
题意:实现一个计算器 +, -, *, /
首先看到这道题我们需要知道*/ 是优先于+, -
所以我们需要一个数据结构去维护这个性质(hashmap)。算法思路是扫描数组先把数放进一个栈,把操作符放进另一个栈,每当遇到操作符,并且操作符栈顶元素的优先级要比我当前元素大了或者和当前元素一样,那需要优先计算(因为你从左到右扫描数组),pop出来进行计算。

比较容易错的点:

  1. pop操作符的时候,操作符栈顶元素的优先级者和当前元素一样也要pop出来
  2. 比如 3/ 2, 和 3-2, 3是先进入栈的元素,2是后进入栈的元素,所以计算的时候要弄清楚顺序
  3. 当你要得到一个字符串中的数字时,i++的最后需要i–,因为最后一位数字得到了,你的i已经跑到下一位不是数字的上面去了
class Solution {
public:

    int calculate(string s) {
        stack<char> oper;
        stack<int> number;
        unordered_map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
        int i = 0;
        for (; i < s.size(); i++) {
            if (s[i] == ' ') {
                continue;
            }
            if (s[i] >= '0' && s[i] <= '9') {
                int x = 0;
                while(i < s.size() && s[i] >= '0' && s[i] <= '9') {
                    x = x * 10 + (s[i] - '0');
                    i++;
                }
                i--;
                number.push(x);
            }
            else {
                while(!oper.empty() && mp[oper.top()] >= mp[s[i]]) {
                    int number1 = number.top();
                    number.pop();
                    int number2 = number.top();
                    number.pop();
                    char op = oper.top();
                    oper.pop();
                    number.push(applyOp(number2, number1, op));
                }
                oper.push(s[i]);
            }
        }

        while(!oper.empty()) {
            int number1 = number.top();
            number.pop();
            int number2 = number.top();
            number.pop();
            char op = oper.top();
            oper.pop();
            number.push(applyOp(number2, number1, op));
        }
        return number.top();

    }

    int applyOp(int x, int y, char op) {
        if (op == '+') {
            return x + y;
        }
        if (op == '-') {
            return x - y;
        }
        if (op == '*') {
            return x * y;
        }
        if (op == '/') {
            return x / y;
        }
        return 0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值