Leetcode 计算逆波兰式(后缀表达式)的值

题目描述

计算逆波兰式(后缀表达式)的值

运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式

例如:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

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 &tokens) {
        stack stack1;
        for (auto x : tokens)
        {
            if (x == "+" || x == "-" || x == "*" || x =="/")
            {
                if (stack1.size() < 2)
                {
                    return 0;
                }

                int b = stack1.top();
                stack1.pop();
                int a = stack1.top();
                stack1.pop();

                if(x=="+")
                {
                    stack1.push(a + b);
                }

                else if(x=="-")
                {
                    stack1.push(a - b);
                }

                else if(x=="*")
                {
                    stack1.push(a * b);
                }

                else if(x=="/")
                {
                    stack1.push(a / b);
                }
            }
            else
            {
                stack1.push(atoi(x.c_str()));
            }
        }
        return stack1.top();
    }
};

 

你可能感兴趣的:(oj)