[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", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

  • 解题思路
    用一个栈来存储数字,从第一个数开始遍历vector<string> tokens,直到最后一个元素。如果遍历到的元素为操作符,则从栈中弹出两个操作数,将其与操作符进行运算,并将运算结果入栈。遍历完成后,栈中的元素即为所求。
  • 实现代码
/*****************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/9 15:07
    *  @Status   : Accepted
    *  @Runtime  : 20 ms
******************************************************************/
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> nums;
        int i = 0;
        int n1, n2;
        while (i < tokens.size())
        {
            if (isToken(tokens[i]))
            {
                n1 = nums.top();
                nums.pop();
                n2 = nums.top();
                nums.pop();
                //特别注意:第二次弹出数字n2为第一个操作数
                nums.push(calc(n2,n1,tokens[i]));
                i++;
            }
            else
            {
                nums.push(strToInt(tokens[i]));
                i++;
            }
        }

        return nums.top();
    }

    int calc(int n1, int n2, string op)
    {
        char ch = op[0];
        switch(ch)
        {
        case '+':
            return n1 + n2;
            break;
        case '-':
            return n1 - n2;
            break;
        case '*':
            return n1 * n2;
            break;
        case '/':
            return n1 / n2;
            break;
        }
    }

    bool isToken(string str)
    {
        if (str.size() == 1 && (str[0] < '0' || str[0] > '9'))
        {
            return true;
        }
        return false;
    }

    int strToInt(string str)
    {
        int sum = 0;
        bool flag = false;
        int i = 0;
        while (str[i] == ' ')
        {
            i++;
        }

        if (str[i] == '-')
        {
            flag = true;
            i++;
        }
        else if (str[i] == '+')
        {
            i++;
        }

        while (i < str.size())
        {
            sum = sum * 10 + str[i++] - '0';
        }

        if (flag)
        {
            return -sum;
        }
        return sum;
    }
};

例如,表达式“8 – ((1 + 2) * 2)”用RPN表示为:8 1 2 + 2 * –

Input Operation Stack Notes
8 压入操作数 8
1 压入操作数 8 1
2 压入操作数 8 1 2
+ 相加 8 3 弹出1、2,压入结果3
2 压入操作数 8 3 2
* 相乘 8 6 弹出3、2,压入结果6
- 相减 2 弹出8、6,压入结果2

算法结束后,栈中只有一个元素,它就是RPN表达式的结果,本例子中结果为2。

时间: 2024-10-13 19:08:37

[LeetCode] Evaluate Reverse Polish Notation的相关文章

[LeetCode 第4题] -- Evaluate Reverse Polish Notation

题目链接: Evaluate Reverse Polish Notation 题目意思: 给的一个表达式,求值 代码: class Solution { public: bool IsOperator(const string &str); int GetStackTop(stack<int> &stack); int evalRPN(vector<string> &tokens); }; bool Solution::IsOperator(const st

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 7 Reverse Integer(翻转整数)

翻译 翻转一个整型数 例1:x = 123, 返回 321 例2:x = -123, 返回 -321 原文 Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you thought about this? (来自LeetCode官网) Here are some good questions to ask before coding. Bonus poi

[LeetCode]151.Reverse Words in a String

题目 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. click to show clarification.

[LeetCode]92.Reverse Linked List II

[题目] Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n

[LeetCode]--345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not incl

[LeetCode]25.Reverse Nodes in k-Group

[题目] Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, onl

leetcode 7 Reverse Integer

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought throu

LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)

原文 给定一个链表,在一定时间内反转这个链表的结点,并返回修改后的链表. 如果结点数不是K的倍数,那么剩余的结点就保持原样. 你不应该在结点上修改它的值,只有结点自身可以修改. 只允许使用常量空间. 例如 给定链表: 1->2->3->4->5 对于 k = 2,你应该返回: 2->1->4->3->5 对于 k = 3,你应该返回: 3->2->1->4->5 翻译 Given a linked list, reverse the