首页 > 代码库 > 求解逆波兰表达式的值

求解逆波兰表达式的值

题目:

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

思路:

这种逆波兰表达式,很明显有栈来求解。需要注意的一点,就是来一个新的符号的时候,将栈中的两个值取出来进行操作,再放回栈中

此时先取出的为num2,后取出的为num1,进行num1 (+-*/) num2 操作

实现:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        if (tokens.size() == 0){
            return 0;
        }
        
        stack<int> st;
        for (int i=0; i < tokens.size(); ++i){
            string s = tokens[i];
            if ("+" == s || "-" == s || "*" == s || "/" == s){
                if (st.size() < 2){
                    return 0;
                }
                
                int num2 = st.top();
                st.pop();
                int num1 = st.top();
                st.pop();
                int result = 0;
                
                if("+" == s){
                    result = num1 + num2;
                }
                else if ("-" == s){
                    result = num1 - num2;
                }
                else if ("*" == s){
                    result = num1 * num2;
                }
                else if ("/" == s){
                    result = num1 / num2;
                }
                st.push(result);
            }
            else{
                st.push(atoi(s.c_str()));
            }
        }
        return st.top();
    }
};

  

求解逆波兰表达式的值