LeetCode: Evaluate Reverse Polish Notation [150]

【题目】

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 str2int(string token){
        int num=0;
        int start=0;
        int isNev = 1;
        //判断符号
        if(token[0]=='-'){isNev=-1; start++;}
        else if(token[0]=='+')start++;
        for(int i=start; i<token.length(); i++){
            num=10*num+(token[i]-'0');
        }
        return num*isNev;
    }
    
    bool isOp(string token){
        if(token=="/" || token=="+" || token=="-" || token=="*")
            return true;
    }
    
    int evalRPN(vector<string> &tokens) {
        stack<int> st;
        for(int i=0; i<tokens.size(); i++){
            if(isOp(tokens[i])){
                //如果是运算符,则计算栈顶元素,然后将结果入栈
                int val1 = st.top(); st.pop();
                int val2 = st.top(); st.pop();
                int res = 0;
                if(tokens[i]=="+")  res = val2 + val1;
                else if(tokens[i]=="-")  res = val2 - val1;
                else if(tokens[i]=="*")  res = val2 * val1;
                else if(tokens[i]=="/")  res = val2 / val1;
                //计算结果入栈
                st.push(res);
            }
            else{
                //数字入栈
                st.push(str2int(tokens[i]));
            }
        }
        return st.top();
    }
};


猜你喜欢

转载自blog.csdn.net/HarryHuang1990/article/details/36204735