[Leetcode] 150. Evaluate Reverse Polish Notation 解题报告

来源:互联网 发布:网络ip地址冲突 编辑:程序博客网 时间:2024/06/06 04:04

题目

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) {        stack<int> st;        for (int i = 0; i < tokens.size(); ++i) {            if (isOperator(tokens[i])) {                int second = st.top();                st.pop();                int first = st.top();                st.pop();                st.push(getValue(first, second, tokens[i][0]));            }            else {                st.push(stoi(tokens[i]));            }        }        return st.top();    }private:    bool isOperator(const string &s) {        if (s == "+" || s == "-" || s == "*" || s == "/") {            return true;        }        else {            return false;        }    }    int getValue(int first, int second, char c) {        if (c == '+') {            return first + second;        }        else if (c == '-') {            return first - second;        }        else if (c == '*') {            return first * second;        }        else if (c == '/') {            return first / second;        }        else {            return -1;        }    }};

0 0
原创粉丝点击