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
遇到数字入栈,遇到运算符将前两个数字出栈,并将结果入栈

class Solution {
public:
    bool checkDigit(string str,int& value){
        bool ret=true;
        int v=0;
        int i=0;
        bool neg=false;
        if(str[0]=='-'){
            i++;
            if(str.size()==1)return false;
            neg=true;
        }
        for(;i<str.length();i++){
            if(str[i]>='0'&&str[i]<='9'){
                v*=10;
                v+=str[i]-'0';
            }
            else return false;
        }
        if(neg)value=-v;
        else value=v;
        return ret;
    }
    int evalRPN(vector<string> &tokens) {
        stack<int> sta;
        int value;
        for(int i=0;i<tokens.size();i++){
            if(checkDigit(tokens[i],value)){
                sta.push(value);
                //cout<<"push"<<value<<endl;
            }
            else{
                int v2=sta.top();
                sta.pop();
                int v1=sta.top();
                sta.pop();
                if(tokens[i]=="+"){
                    sta.push(v1+v2);
                    //cout<<v1<<"+"<<v2<<"="<<v1+v2<<endl;
                }
                else if(tokens[i]=="-"){
                    sta.push(v1-v2);
                    //cout<<v1<<"-"<<v2<<"="<<v1-v2<<endl;
                }
                else if(tokens[i]=="*"){
                    sta.push(v1*v2);
                    //cout<<v1<<"*"<<v2<<"="<<v1*v2<<endl;
                }
                else{
                    sta.push(v1/v2);
                    //cout<<v1<<"/"<<v2<<"="<<v1/v2<<endl;
                }
            }
        }
        return sta.top();
    }
};
View Code
原文地址:https://www.cnblogs.com/superzrx/p/3462029.html