【LeetCode OJ】Evaluate Reverse Polish Notation

Posted on 2014-01-09 11:10  卢泽尔  阅读(382)  评论(0)    收藏  举报

倒霉的LeetCode Online Judge只支持C++和Java……用了多年的python,C++都快忘光了,LeetCode OJ系列就当C++复习回顾吧……


Problem Description

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

According to the wiki page provided in the problem description, the algorithm for evaluating any postfix expression is fairly straightforward:

 1 while there are input tokens left
 2      read the next token from input
 3         if the token is a value (operand)
 4             push it into the stack
 5         else (the token is an operator)
 6             let n be the number of the arguments of the operator
 7             if there are fewer than n values in the stack
 8                 return ERROR (non-sufficient operands in the expression)
 9             else
10                 pop the top n values from the stack
11                 evaluate the expression with the operator and operands
12                 push the result, if any, back into the stack
13 if there is only one value in the stack
14     return the value as the result
15 else
16     return ERROR (too many operands in the expression)

The above is the pseudo-code for evaluating a postfix expression. However, in our case, it is much simpler since there are only four operators, what we need to concern is only to identify the operators and numbers (integer in this case). Therefore, what we need is as follows:

  1. A stack structure;
  2. some functions on string that can determine the string is an integer or an operator.

The C++ code is as follows:

#include <stack>
#include <ctype.h>

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        // The stack to store operators (int values) only
        std::stack<int> res;
        int x,y;
        // Iterate the vector from left to right
        for(std::vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++)
        {
            // If operator, pop and evaluate
            if ( (*it).length() == 1 && !isdigit((*it)[0]) ) {
                y = res.top();
                res.pop();
                x = res.top();
                res.pop();
                if (*it == "+") x += y;
                else if (*it == "-") x -= y;
                else if (*it == "*") x *= y;
                else if (*it == "/") x /= y;
                res.push(x);
            }
            // If operand, push it into the stack
            else res.push( atoi((*it).c_str()) );
        }
        // The only value left in the stack is the final result
        return res.top();
    }
};

 


 

C++ basics:

1. The standard library for stack is std::stack<T> S. The function stack::pop() does not return the value but void value, to get and pop, you need to use stack::top() first to
    get the value and then use stack::pop() to pop the stack top.
2. Use vector iterator to traverse all elements in the vector:

// Assume list is a variable of vector<T> 
for(std::vector<T>::iterator it = list.begin(); it != list.end(); it++)
{
    /* 
     * Do something on each element *it,
     * where it is a pointer type
    */
}

3. Functions to judge the string:

  • isdigit(char): check if a character is a number
  • string::c_str(): convert a string to char*
  • atoi(char*): convert a list of char to a integer