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

逆波兰式,不用说,肯定考虑栈。

主要是题目所给的是字符串的数组,需要多次进行数字到字符串或者字符串到数字的转换,具体实现参考我的blog,整数转字符串,字符串转整数

这里我采用的是c++标准库sstream来实现转换。

代码:

class Solution {
private:
    bool isSymbol(string a){
        return a=="+"||a=="-"||a=="*"||a=="/";
    }
    int Evaluate(int a,int b,char c){
        switch (c)
        {
        case '+':
            return a+b;
            break;
        case '-':
            return a-b;
            break;
        case '*':
            return a*b;
            break;
        case '/':
            return a/b;
            break;
        default:
            break;
        }
    }
public:
    int evalRPN(vector<string> &tokens) {
        stack<string> container;
        for(int i=0;i<tokens.size();++i){
            if(isSymbol(tokens[i])&&!container.empty()){
                string temp2Str=container.top();container.pop();
                string temp1Str=container.top();container.pop();
                int temp2;
                int temp1;
                stringstream s;
                s<<temp2Str;s>>temp2;
                s.clear();
                s<<temp1Str;s>>temp1;
                s.clear();
                
                stringstream s2;
                int res=Evaluate(temp1,temp2,tokens[i][0]);
                s2<<res;
                string resStr=s2.str();
                container.push(resStr);
            }else{
                container.push(tokens[i]);
            }
        }
        stringstream s;
        int result=0;
        string reultStr=container.top();
        s<<reultStr;
        s>>result;
        return result;
    }
};
原文地址:https://www.cnblogs.com/fightformylife/p/4085810.html