[leetcode] Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

使用递归

class Solution {
public:
    bool is_operator(const string &op){
        return op.size()==1&&string("+-*/").find(op)!=string::npos;//是否为操作符
    }

    int evalRPN(vector<string> &tokens) {
        int x,y;
        auto token=tokens.back();//取最后一个操作符
        tokens.pop_back();
        
        if(is_operator(token)){
            y=evalRPN(tokens);//右操作数
            x=evalRPN(tokens);//左操作数
            if(token[0]=='+'){
                x+=y;
            }else if(token[0]=='-'){
                x-=y;
            }else if(token[0]=='*'){
                x*=y;
            }else{
                x/=y;
            }
        }else{
            //size_t i;
            //x=stoi(token,&i);//转为int
            x=atoi(token.c_str());
        }
        return x;
    }
};


使用stack,迭代

class Solution {
public:
    bool is_operator(const string &op){
        return op.size()==1&&string("+-*/").find(op)!=string::npos;
    }
    
    int evalRPN(vector<string> &tokens) {
        stack<string> stk;
        for(auto token:tokens){
            if(!is_operator(token)){
                stk.push(token);
            }else{
                int y=stoi(stk.top());//取栈顶元素,并把string 转 int
                stk.pop();
                int x=stoi(stk.top());
                stk.pop();
                if(token[0]=='+'){
                    x+=y;
                }else if(token[0]=='-'){
                    x-=y;
                }else if(token[0]=='*'){
                    x*=y;
                }else{
                    x/=y;
                }
                stk.push(to_string(x));//int 转 string,并插入到栈顶
            }
        }
        return stoi(stk.top());//结果
    }
};


你可能感兴趣的:([leetcode] Evaluate Reverse Polish Notation)