码迷,mamicode.com
首页 > 其他好文 > 详细

150. Evaluate Reverse Polish Notation

时间:2018-06-26 10:54:59      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:ack   always   i++   each   owa   other   another   计算   get   

问题描述:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won‘t be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

解题思路:

这个是操作符在后面的形式。

我们可以用栈来辅助进行计算:

  当遇见数字字符串时,需要转换成int并进行压栈;

  当遇见操作符字符串时,取出栈顶前两个元素,计算后将结果压栈

 

代码:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stk;
        int ret = 0;
        for(int i = 0; i < tokens.size(); i++){
            if(tokens[i].size() == 1){
                int isOp = isOperator(tokens[i]);
                if(isOp >= 0){
                    int a = stk.top();
                    stk.pop();
                    int b = stk.top();
                    stk.pop();
                    if(isOp == 0){
                        stk.push(a+b);
                    }else if(isOp == 1){
                        stk.push(b-a);
                    }else if(isOp == 2){
                        stk.push(b*a);
                    }else if(isOp == 3){
                        stk.push(b / a);
                    }
                    continue;
                }
            }
            int num = stoi(tokens[i]);
            stk.push(num);
        }
        return stk.top();
    }
private:
    int isOperator(string s){
        if(s == "+")
            return 0;
        if(s == "-")
            return 1;
        if(s == "*")
            return 2;
        if(s == "/")
            return 3;
        return -1;
    }
};

 

150. Evaluate Reverse Polish Notation

标签:ack   always   i++   each   owa   other   another   计算   get   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9227088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!