Evaluate Reverse Polish Notation

题目

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

分析

后缀表达式的简单计算。
数字暂时保存到栈中,从vector取到操作符后,从栈中取2个数字,进行计算,后再保存到栈中。
注意:
1、字符串转换为整数,负数的处理。
2、运算为整数运算。

时间复杂度

一次遍历,O(n)。

输入

    vector<string> s1{"2", "1", "+"};
    vector<string> s2{"2", "1", "+", "3", "*"};
    vector<string> s3{"4", "13", "5", "/", "+"};
    vector<string> s4{"3","-4","+"};

结论

运行时间:12ms。

CODE

#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cstring>
#include <stdexcept>
#include <stack>

using namespace std;

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> sta;
        for (auto s : tokens) {
            if (!isOp(s)) {
                // s is number
                // push it into stack
                sta.push(stringToInt(s));
            } else {
                // s is op
                // take two number from stack
                // calculate and then push into the stack
                int val1, val2;
                val2 = sta.top();
                sta.pop();
                val1 = sta.top();
                sta.pop();

                int res = calc(val1, val2, s);
                sta.push(res);
            }
        }
        return sta.top();
    }

    bool isOp(string s) {
        if (s == "+" || s == "-" || s == "*" || s == "/") {
            return true;
        } else {
            return false;
        }
    }

    int calc(int v1, int v2, string op) {
        if (op == "+") {
            return v1 + v2;
        } else if (op == "-") {
            return v1 - v2;
        } else if (op == "*") {
            return v1 * v2;
        } else if (op == "/") {
            return v1 / v2;
        } else {
            cerr << "Operator is not right: " << op << endl;
        }
    }

    int stringToInt(string s) {
        // Caution: negative numbers
        int val = 0, flag = 1;
        int start = 0;
        if (s[0] == '-') {
            flag = -1;
            start = 1;
        }
        for (int i = start; i < s.size(); ++i) {
            val = val * 10 + s[i] - '0';
        }
        return flag * val;
    }
};

int main()
{
    vector<string> s1{"2", "1", "+"};
    vector<string> s2{"2", "1", "+", "3", "*"};
    vector<string> s3{"4", "13", "5", "/", "+"};
    vector<string> s4{"3","-4","+"};

    Solution so;

    cout << so.evalRPN(s1) << endl;
    cout << so.evalRPN(s2) << endl;
    cout << so.evalRPN(s3) << endl;
    cout << so.evalRPN(s4) << endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值