其他分享
首页 > 其他分享> > LeetCode 150 Evaluate Reverse Polish Notation

LeetCode 150 Evaluate Reverse Polish Notation

作者:互联网

LeetCode 150 Evaluate Reverse Polish Notation

后缀表达式,利用栈就可以轻松计算
c++

class Solution {
public:
    int stack[10005];
    int pos=0;
    int evalRPN(vector<string>& tokens) {
        int l = tokens.size();
        for(int i=0;i<l;i++)
        {
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
            {
                int value1 = stack[--pos];
                int value2 = stack[--pos];
                
                if(tokens[i]=="+")
                {
                    stack[pos++]=value1+value2;
                }
                else if(tokens[i]=="-")
                {
                    stack[pos++]=value2-value1;
                }
                else if(tokens[i]=="*")
                {
                    stack[pos++]=value2*value1;
                }
                else if(tokens[i]=="/")
                {
                    stack[pos++]=value2/value1;
                }
            }
            else
            {
             int value = atoi(tokens[i].c_str());
             stack[pos++]=value;
            }
    
        }
        return stack[0];
    }
};

标签:150,Reverse,Notation,int,Evaluate,tokens,Polish
来源: https://www.cnblogs.com/dacc123/p/10514380.html