【leetcode】Evaluate Reverse Polish Notation(middle)

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

思路:

题目的意思是表达式总是先给出两个操作数,然后再给出对应的操作符。当给出一个这样的表达式后,求出表达式对应的值。

难点是后面操作符的操作数也是表达式。解决方法是用一个栈nums来保存所有没有用过的操作数,当遇到操作符时,栈最上面的两个数字就是操作符对应的操作数。最先遇到的操作符他的操作数一定没有嵌套表达式,所以可以得到值,当运算得到新的数字后,压入栈,作为下一个操作符的操作数。

我的代码:数字与字符串转换的时候比较丑。

int evalRPN2(vector<string>& tokens)
    {
        if(tokens.size() == 1)
            return atoi(tokens[0].c_str());
        vector<string> nums;
        for(int i = 0; i < tokens.size(); i++)
        {
            if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
            {
                string sPreNum, sPostNum, sOp;
                int preNum, postNum, tmp;
                sPostNum = nums.back();
                nums.pop_back();
                sPreNum = nums.back();
                nums.pop_back();
                preNum = atoi(sPreNum.c_str());
                postNum = atoi(sPostNum.c_str());
                sOp = tokens[i];
                switch(sOp[0])
                {
                case ‘+‘:
                    tmp = preNum + postNum; break;
                case ‘-‘:
                    tmp = preNum - postNum; break;
                case ‘*‘:
                    tmp = preNum * postNum; break;
                case ‘/‘:
                    tmp = preNum / postNum; break;
                default:
                    break;
                }
                char ctmp[20];
                sprintf(ctmp, "%d", tmp);
                nums.push_back(ctmp);
            }
            else
            {
                nums.push_back(tokens[i]);
            }
        }
        return atoi(nums[0].c_str());
    }

大神用递归的答案,相对短一些,但是逻辑不好理解。

int eval_expression(vector<string>& tokens, int& pt)
{
    string s = tokens[pt];

    if(s == "+" || s == "-" || s == "*" || s== "/") // tokens[r] is an operator
    {
        pt--;
        int v2 = eval_expression(tokens, pt);
        pt--;
        int v1 = eval_expression(tokens, pt);
        if(s == "+")
            return v1 + v2;
        else if(s == "-")
            return v1 - v2;
        else if(s == "*")
            return v1 * v2;
        else
            return v1 / v2;
    }
    else // tokens[r] is a number
    {
        return atoi(s.c_str());
    }
}

int evalRPN(vector<string> &tokens) {
    int pt = tokens.size()-1;
    return eval_expression(tokens, pt);
}
时间: 2024-10-12 09:10:40

【leetcode】Evaluate Reverse Polish Notation(middle)的相关文章

【LeetCode】Evaluate Reverse Polish Notation

题目 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", "*"]

【Leetcode】Evaluate Reverse Polish Notation答案

一.原题 Evaluate Reverse Polish Notation 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", "+&qu

【Leetcode】Evaluate Reverse Polish Notation JAVA

   一.问题描述 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", "*&

Leetcode 之Evaluate Reverse Polish Notation(41)

很简单的一道题,定义一个栈保留操作数,遇操作符则弹出运算即可. bool isOperator(string &op) { //注意用法 return op.size() == 1 && string("+-*/").find(op) != string::npos; } int evalRPN(vector<string> &tokens) { stack<string> s; for (auto token : tokens)

【leetcode】:Evaluate Reverse Polish Notation (python)

逆波兰式的求解,建立一个类栈容器,遍历给定的逆波兰表达式,遇到数字就push, 遇到操作符就进行出栈,连续出两次,因为给定的四则运算符都是双目的,这里注意下这两个操作数的先后顺序,因为对于加法和乘法没关系,但是对于减法和除法是有先后关系的.然后进行相应的运算,将结果push进栈中. 这里附带说明下python中进行除法运算与c,java系列中的除法的不同,就是向下取整的问题.这种不同表现在两个操作数符号不同时的情况. 在c 中 3 / -5 = 0,但是在python中, 结果却为 - 1.这种

Evaluate Reverse Polish Notation(堆栈)

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", "*"] -&g

【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)

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", "*"] -&g

【leetcode】Linked List Cycle II (middle)

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 思路: 做过,就当复习了. 先用快慢指针判断相交,关键是环开始点的获取. 用上图说明一下,设非环的部分长度为a(包括环的入口点), 环的长度为b(包括环的入口点). 快慢指针相交的位置为绿色的点,距离

【leetcode】Container With Most Water(middle)

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a containe