[leetcode]Evaluate Reverse Polish Notation

逆波兰表达式,情况不是很复杂,用一个栈就解决了。

#include <stack>

#include <string>

using namespace std;



class Solution {

public:

    int evalRPN(vector<string> &tokens) {

        for (int i = 0; i < tokens.size(); i++) {

            string &token = tokens[i];

            if (token == "+") {

                int a = num_stack.top();

                num_stack.pop();

                int b = num_stack.top();

                num_stack.pop();

                int r = a + b;

                num_stack.push(r);

            } else if (token == "-") {

                int a = num_stack.top();

                num_stack.pop();

                int b = num_stack.top();

                num_stack.pop();

                int r = b - a;

                num_stack.push(r);

            } else if (token == "*") {

                int a = num_stack.top();

                num_stack.pop();

                int b = num_stack.top();

                num_stack.pop();

                int r = a * b;

                num_stack.push(r);

            } else if (token == "/") {

                int a = num_stack.top();

                num_stack.pop();

                int b = num_stack.top();

                num_stack.pop();

                int r = b / a;

                num_stack.push(r);

            } else { // number

                bool neg = (token[0] == '-');

                int pos = 0;

                if (neg) {

                    pos = 1;

                }

                int r = 0;

                for (int k = pos; k < token.length(); k++) {

                    r = r * 10 + (token[k] - '0');

                }

                if (neg) {

                    r = -r;

                }

                num_stack.push(r);

            }

        }

        int result = num_stack.top();

        num_stack.pop();

        return result;

    }



private:

    stack<int> num_stack;

};

中间那些部分可以简化出来。

int o1, o2;  

o2 = numeric.top();  

numeric.pop();  

o1 = numeric.top();  

numeric.pop();  



switch(t[0])

{

    case '+':

        numeric.push(o1 + o2);

        break;

    case '-':

        numeric.push(o1 - o2);

        break;

    case '*':

        numeric.push(o1 * o2);

        break;

    case '/':

        numeric.push(o1 / o2);

        break;

}

第二刷,Annie的解法比较简洁。且其中stoi可以直接将字符串转成整数。

你可能感兴趣的:(LeetCode)