cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/237145bd53b0

时间限制:1秒 空间限制:32768K

题目描述

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:
    int evalRPN(vector<string> &tokens) {
        int s_size=tokens.size();
        if(s_size<1) return -1000000;
        stack<int> st;
        int st_size;
        for(int i=0;i<s_size;i++){
            if(tokens[i]=="+" or tokens[i]=="-" or 
               tokens[i]=="*" or tokens[i]=="/"){
                st_size=st.size();
                if(st_size<2)
                    return -1000000;
                int op2=st.top();
                st.pop();
                int op1=st.top();
                st.pop();
                int res;
                if(tokens[i]=="+")
                    res=op1+op2;
                else if (tokens[i]=="-")
                    res=op1-op2;
                else if(tokens[i]=="*")
                    res=op1*op2;
                else{
                    if(op2==0)
                        return -1000000;
                    res=op1/op2;
                }
                st.push(res);
            }
            else{
                st.push(stoi(tokens[i]));
                //st.push(atoi(tokens[i].c_str()));
                //stringstream ss;
                //ss<<tokens[i];
                //int tmp;ss>>tmp;
                //st.push(tmp);
            }
        }
        int res=st.top();
        st.pop();
        if(!st.empty())
            return -1000000;
        return res;
    }
};

运行时间:5ms
占用内存:584k

posted on 2019-05-08 14:05  cherrychenlee  阅读(93)  评论(0编辑  收藏  举报