Leetcode 224 - Basic Calculator(表达式求值1)

23 篇文章 0 订阅
6 篇文章 0 订阅

题意

表达式求值,只含有+, -, (, )。

思路

转逆波兰表示后求值。

转逆波兰的过程:

  1. 扫描字符串,如果是数字直接输出
  2. 如果是),那么一直出栈到遇到(。
  3. 如果是运算符,比较当前运算符op和栈顶运算符top的优先级,如果 topop ,那么出栈直到上述条件不满足。将op放到栈里面。

在处理数字的过程中,注意空格的处理。

代码

class Solution {
public:
    int changeOpToNum(char ch) {
    if (ch == '(') return -1;
    if (ch == ')') return -2;
    if (ch == '+') return -3;
    return -4;
}

bool isOp(char ch) {
    return ch == '(' || ch == ')' || ch == '+' || ch == '-';
}

int pri(int op) {
    if (op == -3 || op == -4) return 1;
}

//v to save RPN
vector<int> v;
void toRPN(string str) {
    stack<int> s;
    int y = -1;
    for (int i = 0; i < str.length(); i++) {
        auto x = str[i];
        if (i == str.length() - 1 && (!isOp(x) || x == ' ')) {
            if (!isOp(x) && x != ' ') v.push_back(y == -1 ? x - '0' : y * 10 + x - '0');
            else if (y != -1) v.push_back(y);
            continue;
        }
        if (x == ' ') continue;
        if (isOp(x)) {
            if (y != -1) v.push_back(y);
            y = -1;
            int op = changeOpToNum(x);
            // ')'
            if (op == -2) {
                while (s.top() != -1) {
                    v.push_back(s.top());
                    s.pop();
                }
                s.pop();
            } else {
                if (op == -1) s.push(op);
                else {
                    while (!s.empty() && s.top() != -1 && pri(op) <= pri(s.top())) {
                        v.push_back(s.top());
                        s.pop();
                    }
                    s.push(op);
                }
            }
        } else {
            if (y == -1) y = 0;
            y *= 10;
            y += x - '0';
        }
    }
    while (!s.empty()) v.push_back(s.top()), s.pop();
}

int calculate(string str) {
    toRPN(str);
    int res = 0;
    stack<int> s;
    for (auto x : v) {
        if (x >= 0) s.push(x);
        else {
            int x2 = s.top(); s.pop();
            int x1 = s.top(); s.pop();
            if (x == -3) s.push(x1 + x2);
            else s.push(x1 - x2);
        }
    }
    return s.top();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值