C++ 13ms 10 lines


  • 0
    int evalRPN(vector<string>& tokens) {
            stack<int> st;                          // use stack to store candidate numbers
            
            for (string token : tokens) {
                if (token == "+" || token == "-" || token == "*" || token == "/") {
                    int b = st.top(); st.pop();     // merge top two numbers in stack
                    st.top() = token == "+" ? st.top() + b : token == "-" ? st.top() - b : token == "*" ? st.top() * b : st.top() / b;
                } else {
                    st.push(stoi(token));           // add candidates in stack
                }
            }
            
            return st.top();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.