Leetcode 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

此题是求解后缀表达式,题目比较简单,开一个数据stack即可,此题的改进版本是引入括号,此时要开一个数据stack和运算符stack
bool isOperator(string& op){
    if(op == "+" ||  op == "-" || op == "*" || op == "/") return true;
    else return false;
}

int calc(int a, int b, char op){
    switch(op){
        case '+':return a+b;
        case '-':return a-b;
        case '*':return a*b;
        case '/':return a/b;
    }
}

int evalRPN(vector<string> &tokens){
    stack<int> num;
    for(int i = 0 ; i < tokens.size(); ++ i){
        if(!isOperator(tokens[i])){
            num.push(atoi(tokens[i].c_str()));
        }else{
            int num2 = num.top(); num.pop();
            int num1 = num.top(); num.pop();
            char op = tokens[i][0];
            num.push(calc(num1,num2,op));
        }
    }
    return num.top();
}

 

 

转载于:https://www.cnblogs.com/xiongqiangcs/p/3794372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值