Leetcode 150. Evaluate Reverse Polish Notation

来源:互联网 发布:程序员老黄历 runjs.cn 编辑:程序博客网 时间:2024/06/06 14:09

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

s思路:
1. 一看结构,就是需要用stack。例如: [“4”, “13”, “5”, “/”, “+”] ,把遇到的数先放进stack,所以当遇到”/”时,stack里面有三个数:4,13,5。遇到”/”,表示取stack 前面的2个数做除法,所以13/5=2,然后把2放进stack;当遇到”+”时,表示取stack 前面的2个数做加法,所以4+2=6,然后把6放进stack
2. 当然stack可以用vector来替代。

class Solution {public:    int evalRPN(vector<string>& tokens) {        //        vector<int> res;        for(string s:tokens){            if(s=="+"||s=="-"||s=="*"||s=="/"){                int op2=res.back();                res.pop_back();                int op1=res.back();                res.pop_back();                if(s=="+")                    res.push_back(op1+op2);                else if(s=="-")                    res.push_back(op1-op2);                else if(s=="*")                    res.push_back(op1*op2);                else if(s=="/"){                    res.push_back(op1/op2);                }            }else                res.push_back(stoi(s));         }        return res.front();    }};
0 0
原创粉丝点击